javascript - 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" 列中的空值违反非空约束。
如果删除我的钩子,代码可以正常工作,但密码不会被加密。
解决方案
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))
推荐阅读
- java - 提取类型 [class org.springframework.http.ResponseEntity] 和内容类型 [text/html;charset=UTF-8] 的响应时出错;
- kubernetes - 如何将容器中的文件映射到 Kubernetes 中的卷中的文件?
- spring-webflux - Spring Flux Reactor 异步消费者完成
- arrays - 从数组定义 JSON 变量
- r - 使用变量进行过滤不会得到与使用常量相同的结果 - R
- dos - 如何使用 C 在 MS-DOS 中检测串口控制器的波特率
- c# - 布尔方法检查列表是否
以一小时间隔连续 - python - 使用 Python 在 3D 轴上绘制直方图
- c# - 流式传输 mp4(流)下载然后播放
- javascript - nodejs express路由无法将req发送到函数