首页 > 解决方案 > Unhandle Promise sequelize hooks 和加密密码

问题描述

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

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" 列中的空值违反非空约束。

如果删除我的钩子,代码可以正常工作,但密码不会被加密。

标签: javascriptnode.jssequelize.jshook

解决方案


setAttributes 接收 3 个参数或一个对象

尝试这个

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))

推荐阅读