Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtuals in mongoose, 'this' is empty object

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?

like image 812
Shahriar HD Avatar asked Mar 04 '16 11:03

Shahriar HD


People also ask

What is virtuals in mongoose?

In Mongoose, a virtual is a property that is not stored in MongoDB. Virtuals are typically used for computed properties on documents.

What is __ V 0 in MongoDB?

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.

What is ref in Mongoose schema?

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.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.


Video Answer


1 Answers

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();
});
like image 170
zangw Avatar answered Oct 02 '22 00:10

zangw