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

查看:33
本文介绍了Mongoose 前/后中间件无法使用 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) {
  ...
});

原因是粗箭头在词法上将函数绑定到当前范围(更多关于 此处,但 TL;DR:粗箭头符号并不意味着是通用的快捷符号,它专门用于创建词法绑定函数),而函数应该在 Mongoose 提供的范围内调用.

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.

这篇关于Mongoose 前/后中间件无法使用 ES6 访问 [this] 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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