Virtuals in mongoose, 'this' is empty object

Viewed 2595

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?

1 Answers
Related