question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

beforeUpdate hook is not being called

See original GitHub issue

Hello, I am trying to call the beforeUpdate hook which uses the same function as beforeCreate hook but it doesn’t even get called:

//user model
'use strict';

var bcrypt = require('bcrypt-nodejs');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
      username: DataTypes.STRING,
      password: DataTypes.STRING,
      email: DataTypes.STRING
    }, {
      instanceMethods: {
        comparePassword: function(candidatePassword, cb) {
          var user = this;
          bcrypt.compare(candidatePassword, user.get('password'), function(err, isMatch) {
            if (err) return cb(err);
            cb(null, isMatch);
          });
        }
      },
      hooks: {
        beforeCreate: hashPassword,
        beforeUpdate: hashPassword
      },
      classMethods: {
        associate: function(models) {
          User.hasMany(models.PasswordReset, {foreignKey: 'userId'});
        }
      }
    } 
  );

  return User;
};


var hashPassword = function(instance, optons, next) {
  console.log(arguments);
  var SALT_FACTOR = 5;

  console.log('in hook');
  console.log('PWD CHANGED? ' + instance.changed('password'));

  if (!instance.changed('password')) return next();

  bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
    if (err) return next(err);

    bcrypt.hash(instance.get('password'), salt, null, function(err, hash) {
      if (err) return next(err);
      instance.set('password', hash);
      console.log(instance.get('password'))
      next();
    });
  });
};

And i try to hash the password before update but the hook doesnt even get called:

    PasswordReset.findOne({ where: { token: req.params.token, expirationDate: {gt: new Date()}}, include: [{model: User}]}).then(function (pwdReset) {
      if (!pwdReset) {
        req.flash('error', 'Password reset token is invalid or has expired.');
        return res.redirect('/forgot');
      }

      User.update({ password: req.body.password }, { where: { id: pwdReset.userId }}).then(function (user){
        req.flash('success', 'Password reset was successful');
        res.redirect('/login');
      });
    }).catch(function (err) {
      return next(err);
    });

Any idea why the password is hashing beforeCreate but not beforeUpdate? What am i doing wrong?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:25 (6 by maintainers)

github_iconTop GitHub Comments

16reactions
AdityaAnand1commented, Oct 14, 2017

@jedwards1211 Oh my god yes. That would be great!

Why is so much of sequeilize so un-intuitive? And why does documentation not tell us about any such quirks?

I have to go treasure hunting for clues on Google/SO/Github to do anything with this library.

7reactions
elcitrovmtgrandecommented, Oct 29, 2018

Hi guys from 2018 ! Thank you for this topic, it helped me a lot a year later ! See you 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

why sequelize beforeUpdate hook doesn't work?
Turn out, that the @BeforeUpdate hook is triggered, when you first find a single record and then update it: await Model.
Read more >
Hooks - Sequelize
Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you...
Read more >
Sequelize hooks explained with code examples
These hooks are JavaScript functions that run before or after an operation has been completed by Sequelize. Let's see an easy example that ......
Read more >
hooks · Sequelize-docs
When using add/set functions the beforeUpdate/afterUpdate hooks will run. The only way to call beforeDestroy/afterDestroy hooks are on associations with ...
Read more >
A Guide to Understanding Vue Lifecycle Hooks - Fjolt
This is not called when doing server side rendering of a site. beforeUpdate() #. Sometimes, you wil change data in your Vue component...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found