如何在typescript环境中使用mongoose.Schema.pre()? userSchema.pre('save',(next)=>{ 如果(!this.isModified('password')){ 返回next(); } this.password=user.encryptPassword(this.password); next(); })

如何在typescript环境中使用mongoose.Schema.pre()? userSchema.pre('save',(next)=>{ 如果(!this.isModified('password')){ 返回next(); } this.password=user.encryptPassword(this.password); next(); }),mongoose,Mongoose,在上面的代码中,typescript编译器告诉我“this”是“globalThis”的类型。但是,在JavaScript中,我们总是认为它具有“MangoOx.Debug”的类型。这里我想访问特定mongoose.Document对象的方法“isModified”,我们只能使用“this”来访问它。 如何使Type脚本编译器知道或考虑“这个”有MyGoOSE的类型。文档 < P>这里的问题是使用箭头函数< /强>。arrow函数将实际上下文带到基础函数。解决方案是删除arrow函数的使用,以便

在上面的代码中,typescript编译器告诉我“this”是“globalThis”的类型。但是,在JavaScript中,我们总是认为它具有“MangoOx.Debug”的类型。这里我想访问特定mongoose.Document对象的方法“isModified”,我们只能使用“this”来访问它。
如何使Type脚本编译器知道或考虑“这个”有MyGoOSE的类型。文档

< P>这里的问题是使用<强>箭头函数< /强>。arrow函数将实际上下文带到基础函数。解决方案是删除arrow函数的使用,以便应用函数的自然上下文。比如:

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

    this.password = user.encryptPassword(this.password);

    next();
});