如何使用猫鼬.Schema.pre() in typescript environment?


userSchema.pre('save',(next)=>{
if(!this.isModified('password')){
return next();
}
this.password = user.encryptPassword(this.password);
next();
})

在上面的代码中,打字稿编译器告诉我"this"是"globalThis"的类型。然而,在JavaScript中,我们总是认为它具有"猫鼬"的类型。文件'。在这里,我想访问某些猫鼬的"isModified"方法。文档对象,我们只能使用"this"来访问它。 如何让打字稿编译器知道或考虑"这个"有猫鼬的类型。公文?

这里的问题是您使用箭头函数。箭头函数会将实际上下文引入基础函数。解决方法是删除箭头函数的使用,以便应用函数的自然上下文。喜欢:

userSchema.pre('save', function (next) {
if(!this.isModified('password')){
return next();
}
this.password = user.encryptPassword(this.password);
next();
});

最新更新