I have a mongodb schema defined using mongoose and I have some sub documents nested over multiple levels. I want to be able to access these (populated) subdocuments within another schema's virtual properties but I can't seem to do so. I seem to be able to access the documents at the first level of nesting but not further down.
Here's an example of my schemas:
const SchemaA = {
name: {type: string}
items: [
{
schemaB: {
type: schema.type.ObjectId,
ref: "B"
}
}
]
}
const SchemaB = {
name: {type: string}
schemaC: {
type: schema.type.ObjectId,
ref: "C"
}
}
const SchemaC = {
types: [{label: {type: String}}]
}
What I want to be able to do is access the SchemaC.types from inside a virtual property on SchemaA.
Here's what I want to achieve:
SchemaA.virtual("types").get(function(){
return this.items.map(item => {
return {name: item.schemaB.name, types: item.schemaB.SchemaC.types}
})
})
From the above item.schemaB
seems to populate just fine but item.schemaB.SchemaC
seems to just be the objectId of schemaC.
I'm not sure if this is even possible, to be honest, but I can't seem to find a definitive answer anywhere online so I'm hoping someone on here can help. Thanks!
So in mongoose you need to use the populate
method.
.populate({
path: 'schemaB',
populate: {
path: 'schemaC'
}
});