Mongoose deep populate a virtual field

Viewed 302

I have a schema structure that is '3 deep' and I find that I can't display information that is at the third level. I'm not sure if it's because this a virtual field, or if I'm doing something wrong.

The collections are programme>project>output. The programme schema looks up the projects like this....

const programmeSchema = new mongoose.Schema({
name: {
    type: String,
},
projects:
    [{ type: mongoose.Schema.ObjectId, ref: 'Project' }],
...
})

Which returns the project. My project schema (middle level) has a virtual field for the outputs collection (third level), like so....

projectSchema.virtual('outputs', {
ref: 'Output',
foreignField: 'project',
localField: '_id'
})

Which works fine when I find and display a single project. However, when I try and display the documents from the outputs collection at the programme (top) level, I can't do it. I've tried various different populates, such as.....

await Programme.findOne({ _id: req.params.id }).populate({
    path: 'projects',
    populate: {
        path: 'outputs'
    }
})

but I'm stumped. I've googled around but aside from one article that I struggled to follow, I can't find anything about this (deep populating a virtual field).

Please could someone tell me where I am going wrong?

0 Answers
Related