繁体   English   中英

序列化:在创建/更新中获取所有传递的数据

[英]Sequelize: getting all passed data in create/update

我将一个普通对象传递给我的UserModel,如下所示:

let user = await User.create(
    {email: 'foo@bar.org', password: 'foo', passwordConfirm: 'foo'}
);

请记住,实际的UserModel具有两个属性:

  1. email
  2. passwordHash

现在,里面beforeValidate ,我想比较passwordpasswordConfirm平等和beforeCreate ,我想bcrypt passwordpasswordHash

不幸的是,到实体/数据到达回调时,它已经被清除并去除了不属于模型定义的任何属性。 这意味着,我只会在实例数据中收到email

我不想在实例外部进行相等比较和哈希处理。 有什么方法可以在实体内部巧妙地使这种逻辑发生?

我假设您的问题中有错别字,并且您想先比较passwordpasswordConfirm (不是passwordHash ),然后再根据密码创建哈希。

对于前者,我建议移动它Sequelize之外,但是如果想要将它传递你应该创建类型的两个新领域的VIRTUAL持有的passwordpasswordConfirm没有他们提交到数据库(甚至创建一个列)然后使用验证器确保它们匹配。 假设验证通过,那么您需要创建passwordHashpassword值。

passwordHash: {
  // this will be persisted to the database
  type: DataTypes.STRING(),
  allowNull: false,
  validate: {
    notEmpty: true,
  },
},
passwordConfirm: {
  // VIRTUAL, not committed
  type: DataTypes.VIRTUAL(),
},
password: {
  // VIRTUAL, not committed
  type: DataTypes.VIRTUAL(),
  // when the field is set, use it to generate a hash
  set: function hashPassword(val) {
    // use the synchronous version, second arg is salt rounds
    this.setDataValue('passwordHash', bcrypt.hashSync(val, 10);
  },
  validate: {
    notEmpty: true,
    // validate that the password and confirmation match
    isConfirmed() {
      return this.password === this.passwordConfirm;
    },
  },
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM