猫鼬之前/之后的中间件软件无法使用ES6访问[this]实例 [英] Mongoose pre/post midleware can't access [this] instance using ES6

查看:66
本文介绍了猫鼬之前/之后的中间件软件无法使用ES6访问[this]实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两难选择,尝试使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆