猫鼬中的虚拟,'this' 是空对象

Virtuals in mongoose, 'this' is empty object

好的,我是猫鼬的新手,正在尝试了解如何使用虚拟属性。这是我一直在测试的示例代码。

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

所以我希望日志是这样的:

1457087841956
2

但输出是

1457087841956
NaN

并且当我在虚拟 getter 的开头记录 'this' 时,它会打印 {}。 我究竟做错了什么?

问题是 virtual 函数中使用的 arrow function,同样的问题可以在 arrow function

ES6 anonymous function and schema methods, the reason is the Lexical this 功能中找到

要解决这个问题,请更改您的代码如下

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