Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); } 
like image 604
Totty.js Avatar asked Jul 19 '12 09:07

Totty.js


People also ask

What is virtual field in mongoose?

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

Are Mongoose virtual functions stored in MongoDB?

Mongoose virtuals are not stored in MongoDB, which means you can't query based on Mongoose virtuals. If you want to query by a computed property, you should set the property using a custom setter or pre save middleware.

What are virtual methods mongoose?

Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document's collection.


1 Answers

Just tried:

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

and worked! ;)

Now by default I use:

  var schemaOptions = {     toObject: {       virtuals: true     }     ,toJSON: {       virtuals: true     }   }; 
like image 95
Totty.js Avatar answered Sep 21 '22 07:09

Totty.js