I have a simple user model as follows :
'use strict';
let hashPassword = (user, options) => {
if (!user.changed('password')) { return; }
return require('bcrypt')
.hash(user.getDataValue('password'), 10)
.then(hash => user.setDataValue('password', hash));
};
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
username: {allowNull: false, type: DataTypes.STRING, unique: true},
email: {allowNull: false, type: DataTypes.STRING, unique: true},
password: {allowNull: false, type: DataTypes.STRING, unique: false},
}, {
hooks: {
beforeCreate: hashPassword,
beforeUpdate: hashPassword
}
});
return User;
};
It works very well on user creation, but the beforeUpdate
hook doesn't seem to work or be called, and the password is saved in plain text in the database.
Where does it come from and how can it be fixed ?
The BeforeUpdate event occurs before changed data in a control or record is updated. expression. BeforeUpdate ( Cancel) expression A variable that represents a Form object. The setting determines if the BeforeUpdate event occurs.
BeforeUpdate ( Cancel) expression A variable that represents a Form object. The setting determines if the BeforeUpdate event occurs. Setting the Cancel argument to True (1) cancels the BeforeUpdate event. Changing data in a control by using Visual Basic or a macro containing the SetValue action doesn't trigger these events for the control.
BeforeUpdate macros and event procedures for a form run only if you change the data in one or more controls in the record. For forms, you can use the BeforeUpdate event to cancel updating of a record before moving to another record.
BeforeUpdatemacros and event procedures for a form run only if you change the data in one or more controls in the record. For forms, you can use the BeforeUpdateevent to cancel updating of a record before moving to another record.
How are you updating the user? There is a difference between getting an instance of the user and updating it and updating by querying the model. The former is an instance update and the latter a bulk update operation (even if your where
filter would return a single item).
This distinction is important because beforeUpdate
is an instance hook so it would be triggered on instance updates only. You can either change the way you update the user or implement a beforeBulkUpdate
hook as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With