Mongoose,访问实例方法内的实例字段的正确方法

问题描述:

我试图在模型上实现实例函数。它会检查expiresAt字段的模型实例值是否超出特定的时间戳。这是我的架构Mongoose,访问实例方法内的实例字段的正确方法

let MySchema = new mongoose.Schema({ 
    userId : { type : ObjectId , unique : true, required: true }, 
    provider : { type : String, required : true}, 
    expiresAt : { type : Number, required : true} 
},{ strict: false }); 

这是实例方法

MySchema.methods.isExpired =() => { 
    console.log(this.expiresAt) // undefined 
    return (this.expiresAt < (Date.now()-5000)) 
}; 

this.expiredAt的价值是不确定的。然后我试图重写功能如下

MySchema.methods.isExpired =() => { 
    try{ 
     console.log(this._doc.expiresAt); 
     console.log((Date.now()-5000)); 
     return (this._doc.expiresAt < (Date.now()-5000)); 
    } catch (e){ 
     console.error(e); 
    } 
}; 

这导致异常

TypeError: Cannot read property 'expiresAt' of undefined为线console.log(this._doc.expiresAt);

什么是访问方法内实例字段正确的方法?

您在您的方法中使用了arrow function,这会更改this值的绑定。

定义function() {}您的猫鼬方法,保持this价值您的实例。

MySchema.methods.isExpired = function() { 
    console.log(this.expiresAt) // is now defined 
    return (this.expiresAt < (Date.now()-5000)) 
}; 
+0

非常感谢@drinchev,我不知道这个在箭头函数中的状态 –