Multiple populates - mongoosejs

后端 未结 8 1757
傲寒
傲寒 2020-12-04 17:33

Just a simple query, for example with a double ref in the model.

Schema / Model

var OrderSchema = new Schema({

    user: {
                 


        
8条回答
  •  天命终不由人
    2020-12-04 18:15

    The best solution in my opinion is arrays when you are populating more than one foreign field on the same level. My code shows that I have multiple populates for different levels.

    const patients = await Patient.find({})
                        .populate([{
                            path: 'files',
                            populate: {
                                path: 'authorizations',
                                model: 'Authorization'
                            },
                            populate: {
                                path: 'claims',
                                model: 'Claim',
                                options: {
                                    sort: { startDate: 1 }
                                }
                            }
                        }, {
                            path: 'policies',
                            model: 'Policy',
                            populate: {
                                path: 'vobs',
                                populate: [{
                                    path: 'benefits'
                                }, {
                                    path: 'eligibility', 
                                    model: 'Eligibility'
                                }]
                            }
                        }]);
    

    As you can see, wherever I needed more than one field of a document populated, I encased the populate key in an array and provided an array of objects, each object having a different path. Most robust and concise way to do it, in my opinion.

提交回复
热议问题