Shahriar HD
Shahriar HD

Reputation: 123

Virtuals in mongoose, 'this' is empty object

ok, i'm new to mongoose and trying to understand how to use virtual properties. this is a sample code that i've been testing.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var objSchema = new Schema({
  created: {type: Number, default: Date.now()},
});

objSchema.virtual('hour').get(()=>{
  //console.log(this);
  var d = new Date(this.created);
  return d.getHours();
});

var obj = mongoose.model('obj', objSchema);

var o = new obj();
o.toObject({virtuals: true});
console.log(o.created);
console.log(o.hour);

so i expect the log to be something like :

1457087841956
2

but the output is

1457087841956
NaN

and when i log 'this' at the beginning of the virtual getter, it prints {}. what am i doing wrong?

Upvotes: 12

Views: 2787

Answers (1)

zangw
zangw

Reputation: 48396

The issue is the arrow function used in virtual function, same issue could be found here ES6 anonymous function and schema methods, the reason is the Lexical this feature of arrow function

To solve it, please change your codes as below

objSchema.virtual('hour').get(function(){
    console.log(this.created);
    var d = new Date(this.created);
    return d.getHours();
});

Upvotes: 39

Related Questions