gpt4 book ai didi

javascript - 未处理的 Promise sequelize hooks 和加密密码

转载 作者:行者123 更新时间:2023-12-03 22:34:53 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com