Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose pre/post midleware can't access [this] instance using ES6

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?

like image 917
Alexandru Olaru Avatar asked Apr 30 '16 16:04

Alexandru Olaru


People also ask

How to use pre in mongoose?

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.

What are pre and post hooks?

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.

What are mongoose Middlewares?

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.

What is pre save hook?

It might be obvious, but a pre-save hook is middleware that is executed when a document is saved.


1 Answers

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.

like image 177
robertklep Avatar answered Oct 10 '22 06:10

robertklep