beforeupdate sequelize does not work

Asked

Viewed 245 times

1

I am trying to make the data update encrypted the user password but simply does not work and does not issue error. Have the following model of sequelize.

import bcrypt from 'bcrypt';

export default (sequelize, DataType) => {
  const Users = sequelize.define('Users', {
    id: {
      type: DataType.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },

    name: {
      type: DataType.STRING,
      allowNull: false,
      validation: {
        notEmpty: true,
      },
    },
    jobTitle: {
      type: DataType.STRING,
      allowNull: false,
      validation: {
        notEmpty: true,
      },
    },

    login:{
      type:DataType.INTEGER,
      allowNull:false,
      validation:{
        notEmpty:true
      }
    },

    password:{
      type:DataType.STRING,
      allowNull:false,
      validation:{
        notEmpty:true
      },
    },
  },
{
  hooks:{
    beforeCreate: user => {
      const salt = bcrypt.genSaltSync();
      user.set('password', bcrypt.hashSync(user.password, salt))
    },
    beforeUpdate: user => {      
      const salt = bcrypt.genSaltSync();
      user.set('password', bcrypt.hashSync(user.password, salt))
    },
  },
  classMethods:{
    isPassword:(encodedPassword, password) => bcrypt.compareSync(password, encodedPassword)
  }
});
  return Users;
}

In the create works perfectly, but no update nor performs the update.

1 answer

0

The beforeUpdate depends on the way the update is performed, because it only works on instance.save() or instance.update(values).

To model.update(values, options) utilize beforeBulkUpdate.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.