Alexandru Olaru
Alexandru Olaru

Reputation: 7092

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?

Upvotes: 16

Views: 2217

Answers (1)

robertklep
robertklep

Reputation: 203231

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.

Upvotes: 38

Related Questions