Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get Mongoose virtuals to be part of the result object

bI'm declaring a virtual that I want to appear as part of the results of its schema's queries, but it's not showing up when I do a console.log on the object. Here's the schema:

var schema = new mongoose.Schema( {     Name: { type: String } }, {     toObject: { virtuals: true } });  schema.virtual("Greet").get(function() {     return "My name is " + this.Name; }); 

Should that toObject not set the virtual as a property of the results of any queries? It does not, nor does schema.set("toObject", { virtuals: true }). Am I doing this right?

like image 918
Mike Pateras Avatar asked Oct 30 '12 06:10

Mike Pateras


People also ask

What are some of the limitations of Mongoose Virtuals as they relate to queries?

Limitations. 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.

How do you get all the values that contains part of a string using Mongoose find?

To get all the values that contains part of a string using Mongoose find , we can use the $regex operator. Books. find({ "authors": { "$regex": "Alex", "$options": "i" } }, (err, docs) => {} );

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.

What are virtual properties in MongoDB?

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

Because you're using JSON.stringify in your console.log call, that invokes the toJSON method on the model instance, not toObject.

So either omit the JSON.stringify in your call:

console.log(results[0]); 

Or set the toJSON option on the schema like you're currently setting the toObject option.

... {     toObject: { virtuals: true },     toJSON: { virtuals: true } }); 
like image 132
JohnnyHK Avatar answered Sep 22 '22 06:09

JohnnyHK