我需要帮助,我需要检查更新子句中的密码是否为“EMPTY”。如果为空,则应更新,否则不更新。
import bcrypt from 'bcrypt-nodejs';
module.exports = function (sequelize, DataTypes) {
const Users = sequelize.define('users', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: true,
autoIncrement: true,
field: 'id_user_acess'
},
username: {
type: DataTypes.STRING,
allowNull: true
},
nome: {
type: DataTypes.STRING,
allowNull: true
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
tableName: 'tb_user_acess',
timestamps: false,
classMethods: {
generateHash: function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
},
comparePassword: function(canditate, password) {
console.log(canditate);
console.log(password);
return bcrypt.compareSync(canditate, password);
}
},
hooks: {
beforeCreate: function (model) {
let user = model.dataValues;
user.password = Users.generateHash(user.password);
return user;
},
beforeUpdate: function (model) {
let user = model.dataValues;
if(user.password == ''){
exclude: user.password;
}else{
user.password = Users.generateHash(user.password);
console.log(user.password);
}
return user;
}
}
});
return Users;
};
我尝试应用一些东西,但没有太大效果
这是我的 Sequelize 模型,请稍稍<3
最佳答案
如果我理解这个问题,如果字段为空,您不想更新用户的密码。如果是这样,只需添加一个检查并返回 null。
function hashPassword(user) {
const password = user.password || user.attributes.password;
if (!user.changed('password')) return null;
return bcrypt.genSaltAsync(5).then(salt =>
bcrypt.hashAsync(password, salt, null).then((hash) => {
user.password = hash; // eslint-disable-line
})
);
}
User.beforeCreate(hashPassword);
User.beforeUpdate(hashPassword);
关于node.js - 使用 Sequelize 更新时忽略密码 ' ',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46043977/