未处理的 Promise sequelize 钩子和加密密码

Unhandle Promise sequelize hooks and encrypt password

我正在尝试在我的数据库中注册一个用户。

const sequelize = require('sequelize')
const { Model, DataTypes } = sequelize
const bcrypt = require('bcrypt')

class User extends Model {

  isPasswordValid(encondedPassword, password) {
   return bcrypt.compareSync(password, encondedPassword)
  }

  static init(sequelize) {
    super.init({
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
        },
      } 
    }, {
      hooks: {
          beforeCreate:  (user, options) => {
            const salt =  bcrypt.genSaltSync()
            user.setAttributes('password', bcrypt.hashSync(user.password, salt))
          }
      },
      sequelize
    })
  }
}

module.exports = User

但是当我调用 User.create({email, password}) 时,它给了我错误:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: "password" 列中的空值违反了非空约束。

如果 delete my hook 代码可以正常工作,但密码不会被加密。

setAttributes receive 3 arguments or an object

试试这个

user.setAttributes('setAttributes', 'password', bcrypt.hashSync(user.password, salt))
//OR
user.setAttributes({password: bcrypt.hashSync(user.password, salt)})

使用更简单setDataValue

user.setDataValue('password', bcrypt.hashSync(user.password, salt))