Shabin Muhammed
Shabin Muhammed

Reputation: 1142

Mongoose, correct method to access instance fields inside instance method

I'm trying to implement an instance function on a Model. It checks whether a model instance's value for the field expiresAt is beyond a particular timestamp. This is my schema

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

This is the instance method

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

But the value for this.expiredAt is undefined. Then I tried to rewrite the function as follows

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

This causes an exception

TypeError: Cannot read property 'expiresAt' of undefined for the line console.log(this._doc.expiresAt);

What is the correct method to access instance fields inside the method?

Upvotes: 1

Views: 1110

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

You are using arrow function in your method, which changes the binding of this value.

Definition with function() {} of your mongoose methods, keep this value to your instance.

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

Upvotes: 5

Related Questions