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

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...