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?
In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents.
The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.
The ref option is what tells Mongoose which model to use during population, in our case the Story model. All _id s we store here must be document _id s from the Story model. Note: ObjectId , Number , String , and Buffer are valid for use as refs.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With