我正在尝试在数据库中注册用户。
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:“密码”列中的空值违反了非空约束。
如果删除我的钩子,代码可以正常工作,但密码不会被加密。
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句