34

I saw in another answer that in order to include the virtual fields you must do like https://groups.google.com/forum/?fromgroups#!topic/mongoose-orm/HjrPAP_WXYs

var schemaOptions = {
  toJSON: {
    virtuals: true
  }
};

which I've done;

Now in the Schema:

 new Schema({...}, schemaOptions);

But still so, the data doesn't include the virtual.. :s

But like this works:

var docsCallback = function(err, docs){
    var i = docs.length;
    var nDocs = [];
    while(i--){
        nDocs[i] = docs[i].toObject({virtuals: true});
    }
    done(nDocs);
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Totty.js
  • 15,563
  • 31
  • 103
  • 175

3 Answers3

58

Just tried:

  var schemaOptions = {
    toObject: {
      virtuals: true
    }
  };

and worked! ;)

Now by default I use:

  var schemaOptions = {
    toObject: {
      virtuals: true
    }
    ,toJSON: {
      virtuals: true
    }
  };
Totty.js
  • 15,563
  • 31
  • 103
  • 175
13

You can do this way as well:

docs.set('toJSON', { virtuals: true });
Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164
0

For me it worked only after adding getters: true to schema options, as mentioned in mongoose docs, i.e.

var schemaOptions = {
  toObject: {
    getters: true
  },
  toJSON: {
    getters: true
  }
};
sr9yar
  • 4,850
  • 5
  • 53
  • 59
Yair
  • 51
  • 6