Mongoose pre / post midleware cannot access this instance using ES6

I have a dilemma when trying to add some preliminary logic to the mongoose model using the pre middleware and cannot access the this instance as usual.

 UserSchema.pre('save', next => { console.log(this); // logs out empty object {} let hash = crypto.createHash('sha256'); let password = this.password; console.log("Hashing password, " + password); hash.update(password); this.password = hash.digest('hex'); next(); }); 

Question: * Is there a way to access the this instance?

+7
mongoose
source share
1 answer

A bold arrow ( => ) is not useful in this situation. Instead, just use the deprecated anonymous function:

 UserSchema.pre('save', function(next) { ... }); 

The reason is that the bold arrow lexically binds the function to the current scale (more on this here , but TL; DR: the designation of the bold arrow does not mean to be a generalized musical notation, it meant specifically to create lexically related functions), whereas the function should be called in the area provided by Mongoose.

+21
source share

All Articles