why sequelize beforeUpdate hook doesn't work?

8.6k views Asked by At

I have a simple user model with 2 hooks.

User.beforeCreate(setSaltAndPass)
User.beforeUpdate(setSaltAndPass)

the first works perfectly but the beforeUpdate does not run, according to the documentation you should have no problem executing the following

await User.update(user, {
             where: {
               id
             }

         })

is saving the key as plain text, it does not happen for example with the create. Curiously beforeBulkUpdate is executed when it is updated.

this is the callback, the detail is that in bulk I don't have the changed property or at least I don't know how to access it.

const setSaltAndPass = user => {
   if (user.changed('pass')) {
     user.salt = User.generateSalt()
     user.pass = User.encriptPass(user.pass(), user.salt())
   }
}

does its job, but hook its not excecuted.

5

There are 5 answers

1
Amir On

Use beforeBulkUpdate instead on beforeUpdate

0
Guido Glielmi On

If using classes, you could override the Model method as follows:

const { Model } = require('sequelize');

class MyModel extends Model {
  static async update(values, options) {
    // Maybe custom logic here... 
    return super.update(values, { ...options, individualHooks: true });
  }
}
0
Pugazhenthi On

Set individualHooks: true, in the options block

await User.update(user, {
  where: {
    id
  },
    individualHooks: true,
});
0
Jaspal Singh On

You need to set the individualHooks to true in update function, please see the below example

const [, [user]] = await User.update(body, {
      where,
      returning: true,
      attributes: ['userId', 'email'],
      individualHooks: true,
    });
0
Niko Mol On

I had the same issue in TS just now. Turn out, that the @BeforeUpdate hook is triggered, when you first find a single record and then update it:

await Model.findOne(options).then((result) => { 
    result.update(options); 
});

In case you prefer the Model.update(...) approach, you can use the @BeforeBulkUpdate hook instead.

Found this info here: https://github.com/sequelize/sequelize/issues/6253

This worked for me, hope it helps!