为什么Mongoose的预钩不能与Fat-arrow函数语法一起使用

Jam*_*mes 2 mongoose node.js

我正在尝试使用一个简单的预钩猫鼬删除像这样的文档的任何引用:

PostSchema.pre("remove", async () => {
  await Comment.remove({ _postId: this._id }).exec();
  await User.update({ $pull: { _posts: this._id } }).exec();
});
Run Code Online (Sandbox Code Playgroud)

上面的粗箭头语法似乎不起作用-尽管删除了Post文档,但是Comment和User模型并未相应更新。相反,我不得不使用旧语法(根据猫鼬文档)来使钩子正常工作,如下所示:

PostSchema.pre("remove", async function() {
  await Comment.remove({ _postId: this._id }).exec();
  await User.update({ $pull: { _posts: this._id } }).exec();
});
Run Code Online (Sandbox Code Playgroud)

我发现这很奇怪,除非我当然做错了。这是预期的行为吗?

Art*_* P. 5

因为this指向全局范围,而不是箭头函数中的函数范围。在这种情况下,请function(){}改用

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions

编辑:类似的问题:https//stackoverflow.com/a/49441708/7526159