Chris Rutherford
Chris Rutherford

Reputation: 1672

Mongoose .pre not saving hashed passwords to the DB

working with Passport and mongoose, and I'm trying to hash the passwords saved to the database, and it's simply not happening.

I have the model defined, and I can confirm that the object is being written to the database, so it must be in the block where my pre-save middleware is defined.

UserSchema.pre('save', (next) => {
    console.log('Pre-Save Hash has fired.')
    let user = this;
    bcrypt.genSalt(10, (err, salt) => {
        if (err) console.error(err);
        bcrypt.hash(user.password, salt, (err, hash) => {
            user.password = hash;
            next();
        });
    });
});

Not sure why it's saving the password field in clear text when I clearly have something in place. It's probably implemented incorrectly. (the console.log in the middleware does log to the console.)

Upvotes: 0

Views: 339

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

Try using a regular function instead of an arrow function for your pre-save callback to ensure that this references the document being processed:

UserSchema.pre('save', function (next) {
  console.log('Pre-Save Hash has fired.')
  let user = this
  bcrypt.genSalt(10, (err, salt) => {
    if (err) console.error(err)
    bcrypt.hash(user.password, salt, (err, hash) => {
      user.password = hash
      next()
    })
  })
})

Upvotes: 0

Related Questions