Virtuals in mongoose, 'this' is empty object Virtuals in mongoose, 'this' is empty object mongodb mongodb

Virtuals in mongoose, 'this' is empty object


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