Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...