Multiple populates - mongoosejs

后端 未结 8 1723
傲寒
傲寒 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:14

    This has probably been resolved already, but this is my take on multiple & deep population in Mongodb > 3.6:

    OrderModel.find().populate([{
        path: 'user',
        model: 'User'
    }, {
        path: 'meal',
        model: 'Meal'
    }]).exec(function(err, order) {
        if(err) throw err;
        if(order) {
            // execute on order
            console.log(order.user.username); // prints user's username
            console.log(order.meal.value);    // you get the idea
        }
    });
    

    There are probably other ways to do this, but this makes very readable code for beginners (like me)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题