Mongoose virtual fields included in toJSON by default: schemaOptions.toJSON.virtuals = true; still doesn't include virtual fields by default

Totty.js picture Totty.js · Jul 19, 2012 · Viewed 14k times · Source

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

Answer

Totty.js picture Totty.js · Jul 19, 2012

Just tried:

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

and worked! ;)

Now by default I use:

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