Mongoose virtual games, 'this' is an empty object

ok, I'm new to mongoose and trying to figure out how to use virtual properties. This is an example of the code I tested.

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 will be something like:

 1457087841956 2 

but the way out

 1457087841956 NaN 

and when I log 'this' at the beginning of the virtual receiver, it prints {}. What am I doing wrong?

+6
source share
1 answer

The problem is the arrow function used in the virtual function, the same problem can be found here anonymous ES6 function and circuit methods , the reason is this function Lexical arrow function

To solve this problem, change your codes below:

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

All Articles