我正在尝试在我的数据库中注册一个用户。
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"列中的空值违反非空约束。
如果删除我的钩子(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))
关于javascript - 未处理的 Promise sequelize hooks 和加密密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62107010/