Mongoose pre save is using incorrect "this" context? Mongoose pre save is using incorrect "this" context? mongoose mongoose

Mongoose pre save is using incorrect "this" context?


Problem here is a fat arrow functions. You must rewrite your callback with simple functions. Here small example to show the diff

var obj = {};obj.func1 = function () {    console.log(this === obj);};obj.func2 = () => {    console.log(this === obj);};obj.func1(); // trueobj.func1.bind(obj)(); // trueobj.func2(); // falseobj.func2.bind(obj)(); // false


I was able to figure out the issue. It turns out Arrow Functions in ES6 preserve the context of the declaring scope rather than using the context of the calling scope so changing the code to the below fixed the issue.

userSchema.pre('save', function (next) {    Bcrypt.genSalt((err, salt) => {        if (err) {            return next(err);        }        Bcrypt.hash(this.password, salt, (err, encrypted) => {            if (err) {                return next(err);            }            this.password = encrypted;            next();        });    });});

Thank you Michelem for giving me the idea that ES6 may have been the culprit.


I think it should be:

userSchema.pre('save', (next) => {    var user = this;    // Try this    // console.log(user);    Bcrypt.genSalt(function (err, salt) {        if (err) {            return next(err);        }        Bcrypt.hash(user.password, salt, null, function (err, encrypted) {            if (err) {                return next(err);            }            user.password = encrypted;            next();        });    });});

But please check user is the right object.