0

I am facing a weird issue.

The below code throws error and it uses arrow function

UserSchema.pre('save', next => {
  const SALT_FACTOR = 5;

  if (!this.isModified('password')) return next();

  bcrypt.genSalt(SALT_FACTOR, (err, salt) => {
    if (err) return next(err);

    bcrypt.hash(this.password, salt, null, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      next();
    });
  });
});

The below code works fine and it uses normal function.

UserSchema.pre('save', function(next) {
  const SALT_FACTOR = 5;

  if (!this.isModified('password')) return next();

  bcrypt.genSalt(SALT_FACTOR, (err, salt) => {
    if (err) return next(err);

    bcrypt.hash(this.password, salt, null, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      next();
    });
  });
});

Anyone has an idea why arrow function throws below error?

TypeError: this.isModified is not a function

Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
  • Well, the arrow function will have `this` bound to its lexical scope. So, I imagine it's probably not going to be the `this` you want. – VLAZ Sep 18 '18 at 12:22
  • The way `this` is handled is one of the fundamental differences between `=>` functions and traditional functions. – Pointy Sep 18 '18 at 12:22

1 Answers1

0

You want might to reference this : https://stackoverflow.com/a/44080978/1971378. gist: arrow functions seal this when defined.

trk
  • 2,106
  • 14
  • 20