Reputation: 1672
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
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