Here is some es5 code in a pre
hook that works while saving a user:
// On Save Hook, encrypt password
// Before saving a model, run this function
userSchema.pre('save', function(next) {
// get access to the user model
const user = this;
// generate a salt then run callback
bcrypt.genSalt(10, function(err, salt) {
if (err) { return next(err); }
// hash (encrypt) our password using the salt
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) { return next(err); }
// overwrite plain text password with encrypted password
user.password = hash;
next();
});
});
});
Here is my es6
version of the same code:
userSchema.pre('save', (next) => {
// get access to the user model
const user = this;
// generate a salt then run callback
bcrypt.genSalt(10, (err, salt) => {
if (err) { return next(err); }
// hash (encrypt) our password using the salt
bcrypt.hash(user.password, salt, null, (err, hash) => {
if (err) { return next(err); }
// overwrite plain text password with encrypted password
user.password = hash;
next();
});
});
});
This fails for some reason and I don't understand why! There are no errors thrown. The user does not get saved with the hashed password string - just plain text.
If I change just the first line of code in the es6 example:
userSchema.pre('save', function(next) {...
the rest of it works
I don't understand if this is a problem with the way mongoose hooks work or am I writing javascript wrong?