Mongoose 钩子不适用于 Typescript

Eri*_*ric 4 mongoose typescript

那么有谁知道为什么我在使用 mongoose hook 和引用this. 我没有使用箭头函数,并且我知道它的词法作用域问题,但即使使用这样的匿名函数:

UserSchema.pre("save", function(next) {
    console.log(this.password);
    next();
});
Run Code Online (Sandbox Code Playgroud)

确切的错误消息是

'this' implicitly has type 'any' because it does not have a type annotation.
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决这个问题吗?

顺便说一句,我正在使用 Typescript 2.5.2 / NodeJS 8.2.1

谢谢!

小智 8

尝试这个:

schema.pre("save", function(this: UserModel, next: any) {
  console.log(this.password);
  next();
});
Run Code Online (Sandbox Code Playgroud)

我认为您收到错误是因为您可能有一个打字稿配置来检查隐式的any。如果您在钩子函数的参数中键入“ this ”,则错误应该得到解决。