Modify attributes in beforeCreate hook

Other topics

Example working with a library that doesn't use Promise

function cryptPassword(password, callback) {
  bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
    if (err)
      return callback(err);

    bcrypt.hash(password, salt, null, function(err, hash) {
      return callback(err, hash);
    });
  });
}

User.beforeCreate((user, options, cb) => {
  cryptPassword(user.password, (err, hash) => {
    if (err) return cb(err);

    user.password = hash;
    // invoking the finish callback is important!
    return cb(null, options);
  });    
});

Example working with a library that doesn't use Promise

User.beforeCreate(function(user, options) {
  return hashPassword(user.password).then(function (hashedPw) {
  user.password = hashedPw;
  });
})

Syntax:

  • beforeCreate(instance)
  • beforeCreate(instance, options, fn)

Contributors

Topic Id: 9002

Example Ids: 27990,27991

This site is not affiliated with any of the contributors.