【发布时间】:2019-02-04 02:04:48
【问题描述】:
我在我的用户模型上使用 beforeUpdate 钩子在密码更改时对密码进行哈希处理。但是只要发送任何字段,它就会更改密码。如何在返回钩子函数之前检查密码是否已发送?
我尝试将退货放在if(user.password !== '') 中。但它不起作用,可能是因为它引用了存储的密码。
这是我的代码:
const Sequelize = require('sequelize')
const connection = require('../../../db/connection.js')
const bcrypt = require('bcrypt')
const User = connection.define('user', {
fullName: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
validate: { isEmail: true }
},
password: {
type: Sequelize.STRING,
allowNull: false
}
})
// Create hash for password, on before create, using bcrypt
User.beforeCreate((user, options) => {
return bcrypt.hash(user.password, 10).then(hash => {
user.password = hash
})
})
// Create hash for password, on before update, using bcrypt
User.beforeUpdate((user, options) => {
return bcrypt.hash(user.password, 10).then(hash => {
user.password = hash
})
})
module.exports = User
【问题讨论】:
-
嗨,你能解决这个问题吗?
标签: node.js sequelize.js