0

Here is some es5 code in a pre hook that works while saving a user:

// On Save Hook, encrypt password
// Before saving a model, run this function
userSchema.pre('save', function(next) {
  // get access to the user model
  const user = this;

  // generate a salt then run callback
  bcrypt.genSalt(10, function(err, salt) {
    if (err) { return next(err); }

    // hash (encrypt) our password using the salt
    bcrypt.hash(user.password, salt, null, function(err, hash) {
      if (err) { return next(err); }

      // overwrite plain text password with encrypted password
      user.password = hash;
      next();
    });
  });
});

Here is my es6 version of the same code:

userSchema.pre('save', (next) => {
  // get access to the user model
  const user = this;

  // generate a salt then run callback
  bcrypt.genSalt(10, (err, salt) => {
    if (err) { return next(err); }

    // hash (encrypt) our password using the salt
    bcrypt.hash(user.password, salt, null, (err, hash) => {
      if (err) { return next(err); }

      // overwrite plain text password with encrypted password
      user.password = hash;
      next();
    });
  });
});

This fails for some reason and I don't understand why! There are no errors thrown. The user does not get saved with the hashed password string - just plain text.

If I change just the first line of code in the es6 example:

userSchema.pre('save', function(next) {...

the rest of it works

I don't understand if this is a problem with the way mongoose hooks work or am I writing javascript wrong?

Amit Erandole
  • 10,436
  • 20
  • 60
  • 92
  • 3
    this is due to line `const user = this;` – Gaurav joshi Jan 17 '17 at 04:37
  • 1
    print this in both the cases and you will see the diff – Gaurav joshi Jan 17 '17 at 04:38
  • Basically, the `this` for `() => {}` is the `this` of the surrounding scope. The `this` for a function can be manipulated by how the function is called – Jaromanda X Jan 17 '17 at 04:43
  • 1
    What @Gauravjoshi is trying to say is, in the first case, `this` refers to the callback function scope, while in the second case, `this` refers to the scope of the same closure `userSchema` is in. That's the whole point of arrow function - it inherits the scope of outer scope. – Kousha Jan 17 '17 at 04:44
  • So how do I fix this in es6? Could you add an answer below with explanations? – Amit Erandole Jan 17 '17 at 04:45
  • fix by using `function` ... ... `()=>{}` isn't a ***replacement*** for `function`, it is a tool to use in the right circumstances – Jaromanda X Jan 17 '17 at 04:46
  • 1
    by the way, your es5 code isn't ... the concept of `const` confuses and angers es5 :p – Jaromanda X Jan 17 '17 at 04:59

0 Answers0