7

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 ?

2 Answers 2

13
+50

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.

2
  • It looks like you are right, I use db.user.update(..., {where: {id: req.params.userId}});. Thank you very much
    – Magix
    Oct 20, 2017 at 10:44
  • can you post sample code, because i can't find what parameters actually are Feb 28, 2018 at 6:13
1

To offer an alternative to Unglückspilz answer. You can also add the option

{ individualHooks: true }

Note: methods like bulkCreate do not emit individual hooks by default - only the bulk hooks. However, if you want individual hooks to be emitted as well, you can pass the { individualHooks: true } option to the query call. However, this can drastically impact performance, depending on the number of records involved (since, among other things, all instances will be loaded into memory).

https://sequelize.org/master/manual/hooks.html#model-hooks

1
  • const user = await User.update(req.body,{ where: { id }, individualHooks: true}); Apr 15, 2022 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.