【问题标题】:Mongoose, correct method to access instance fields inside instance method猫鼬,访问实例方法内的实例字段的正确方法
【发布时间】:2017-08-06 17:28:42
【问题描述】:

我正在尝试在模型上实现实例函数。它检查字段expiresAt 的模型实例值是否超出特定时间戳。这是我的架构

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);

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

【问题讨论】:

    标签: node.js mongoose mongoose-schema


    【解决方案1】:

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

    使用 function() {} 定义您的 mongoose 方法,将 this 值保留给您的实例。

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

    【讨论】:

    • 非常感谢@drinchev,我不知道箭头函数中 this 的状态
    • 本能地做了一个箭头函数,忘记了这个副作用。
    猜你喜欢
    • 2023-03-08
    • 2015-09-01
    • 2015-02-12
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多