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?
I ended up here doing something really silly. I was using
Doc.find
instead ofDoc.findOne
and so I was trying to access the virtual on the document array instead of on the document itself.Because you're using
JSON.stringify
in yourconsole.log
call, that invokes thetoJSON
method on the model instance, nottoObject
.So either omit the
JSON.stringify
in your call:Or set the
toJSON
option on the schema like you're currently setting thetoObject
option.