Mongoose populating array of subdocuments

梦想与她 提交于 2019-12-12 13:19:30

问题


Apologies if this has already been asked, my searches did not turn up the same situation. I have two schemas something like the below:

var experimentSchema = new mongoose.Schema({

    name  : 'string'
    elements :  [{
        type : mongoose.Schema.ObjectId, 
        ref: 'Element'
    }],
    resources : [{
        type : mongoose.Schema.ObjectId,
        ref  : 'Resource'
    }],

})


var elementSchema = new mongoose.Schema({
    name : 'string',
    component : {
        type : mongoose.Schema.ObjectId,
        ref  : 'Component'
    }
})

I want to perform a deep population so that when I request an experiment I get an object with an array of elements and resources and for each of the elements the field component has also been populated.

I have tried a few things along the lines of:

Experiment.findOne(query).populate(['resources','elements','elements.component']).exec(...)

without success. Can anyone provide the correct syntax for this type of operation?

Thanks in advance!


回答1:


hope this helps.

models.User.findOne(query)
      .populate([{
        path: 'elements',
        populate: { 
             path:  'components', 
             model: 'Component'
            }
      },{
        path:'resources'
      }])
      .exec(...)


来源:https://stackoverflow.com/questions/40470823/mongoose-populating-array-of-subdocuments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!