I have dilemma, trying to add some pre-logic to a mongoose model using pre
middleware and can not 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?
Pre middleware functions are executed one after another, when each middleware calls next . const schema = new Schema(..); schema. pre('save', function(next) { // do stuff next(); }); In mongoose 5.
Pre- and post-execution hooks are Processing scripts that run before and after actual data processing is performed. This can be used to automate tasks that should be performed whenever an algorithm is executed.
Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.
It might be obvious, but a pre-save hook is middleware that is executed when a document is saved.
The fat arrow notation (=>
) is not useful in this situation. Instead, just use the old fashioned anonymous function notation:
UserSchema.pre('save', function(next) {
...
});
The reason is that the fat arrow lexically binds the function to the current scope (more on that here, but TL;DR: the fat arrow notation is not meant to be a generic shortcut notation, it's meant specifically to create lexically bound functions), whereas the function should be called in a scope provided by Mongoose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With