Solvedmongoose Is not a function ERROR - this.isModified is not a function

When I use following code:

userSchema.pre('save', (done) => {
  if(this.isModified('password')) {
    bcrypt.hash(this.password, null, null, (err, hash) => {
      if(err) return next(err);

      this.password = hash;
      this.updated_at = new Date().toISOString();
      done();
    });
  } else {
    return done();
  }
});

I receive following Error:

TypeError: this.isModified is not a function
    at model.userSchema.pre (C:\code\project\core\models\user.js:26:11)
    at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
    at model.Object.defineProperty.value.fn (C:\code\project\node_modules\mongoose\lib\schema.js:221:11)
    at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
    at C:\code\project\node_modules\mongoose\lib\schema.js:196:17
    at C:\code\project\node_modules\kareem\index.js:127:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

Problem:

  • this is not a Document, Query or Schema. It's value is {}

How can I solve that?

12 Answers

✔️Accepted Answer

You are using an arrow operator for the callback, which changes the scope of this. If you define a regular callback you should be fine, e.g.:

userSchema.pre('save',  function(done)  {
});