Hey guys,
After searching for a bit on Google I found no relevant answers to why populated document virtuals are not set when the parent document they are populated on has its Document#toObject method invoked.
Example Schema definitions:
mongoose = compound.mandyGet('mongoose')
Image = new mongoose.Schema
stem:
type: String
unique: true
searchable: true
tags: []
ext: String
types: []
_job:
type: mongoose.Schema.Types.ObjectId
ref: 'Scope'
Image.virtual('urls').get ->
urls = {}
urls[type]= "#{@stem}-#{type}.#{@ext}" for type in @types
urls
Image.set 'toObject', virtuals: true
Product = new mongoose.Schema
images: [{
type: mongoose.Schema.Types.ObjectId
ref: 'Image'
}]
compound.models.Image = compound.mandyGet('mongoose').model 'Image', Image
compound.models.Product = compound.mandyGet('mongoose').model 'Product', Product
Notice how Image has been flagged as virtuals: true
However, when you run:
c.Model.Product
.findById('fakeid')
.populate('images')
.exec (err, product)=>
c.res.json product # here it is turned into an object to send to the client but will not have image.urls defined on the client-side
The virtuals from the Image Schema will not be returned in this scenario. To fix this problem you would have to set the Product schema virtuals:true.
I am not sure if this is easily fixable, as recursively checking populated documents for virtuals looks like it will cause issues elsewhere, but I thought it bore documentation.