猫鼬之前/之后的中间件软件无法使用ES6访问[this]实例 [英] Mongoose pre/post midleware can't access [this] instance using ES6
问题描述
我有两难选择,尝试使用pre
中间件向猫鼬模型添加一些预逻辑,并且无法像往常一样访问this
实例.
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();
});
问题:*是否可以访问this
实例?
Question: *Is there a way to access the this
instance?
推荐答案
在这种情况下,粗箭头符号(=>
)无效.相反,只需使用老式的匿名函数表示法即可:
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.
这篇关于猫鼬之前/之后的中间件软件无法使用ES6访问[this]实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!