【问题标题】:Sequelize: getting all passed data in create/updateSequelize:在创建/更新中获取所有传递的数据
【发布时间】:2017-04-26 03:37:24
【问题描述】:

我将一个普通对象传递给我的 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

我不想在实例之外进行相等比较和散列。有什么方法可以巧妙地让这个逻辑发生在实体内部?

【问题讨论】:

    标签: javascript node.js typescript sequelize.js


    【解决方案1】:

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

    对于前者,我建议将其移到 Sequelize 之外,但如果您确实想要将其传入,您应该创建两个 VIRTUAL 类型的新字段来保存 password 和 @ 987654326@ 无需将它们提交到数据库(甚至创建列),然后使用验证器确保它们匹配。假设验证通过,您将根据 password 值创建 passwordHash

    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;
        },
      },
    },
    

    【讨论】:

    • 这是一个很好的解决方案 - 非常感谢。我喜欢VIRTUAL 数据类型的解决方案,并且能够使用 Sequelize 的内置验证。你是对的 - 这是我现在修复的类型。塔!
    猜你喜欢
    • 1970-01-01
    • 2020-05-24
    • 2013-08-20
    • 2017-09-19
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    相关资源
    最近更新 更多