This works fine for the registration process...
// Hash/Salt Password
AccountSchema.pre('save', function(next) {
const account = this;
bcrypt.hash(account.password, 10, function(err, hash) {
if (err) return next(err);
account.password = hash;
next();
});
});
...however, if a registered user wants to change their password, I can't seem to bcrypt when updating the document.
I'm looking for a direct solution, using a similar approach to the example above.
UPDATE:
Oddly enough, I found a solution. This works...
AccountSchema.pre('findOneAndUpdate', function(next) {
const account = this.getUpdate();
bcrypt.hash(account.password, 10, (err, hash) => {
this.getUpdate().password = hash;
next();
})
});
...while this doesn't...
AccountSchema.pre('findOneAndUpdate', function(next) {
const account = this.getUpdate();
bcrypt.hash(account.password, 10, function(err, hash) {
if (err) return next(err);
this.getUpdate().password = hash;
next();
})
});
...but I have no idea why. The difference is basically the fat arrow plus error handling, and I'm very confused about how it would make such a big difference - since pre('save', ... ) had zero issues with function(err, hash) or if (err) return next(err);.
If anyone can explain why, it would be greatly appreciated.
j
stuff ;)
fat arrow is a closure that binds the this reference to the outer context.
() => 'foo';equals
function () { return 'foo'; }.bind(this)every function is it's own object in JS so
thisinfunctionpoints to the function itself. with fat-arrow it does not.does this help?