Search code examples
node.jsmongodbmongoosemongoose-populate

Mongoose populate multiple levels


I have an users collection which has an orders key:

orders:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Order'
    }]

The orders schema has an array of products:

contents:[{
        product:{
            type:String,
            ref:'Product'
        },
        size:String,
        color:String,
        price:Number
    }]

and the product schema has _id as:

_id:{
        type:String,
        unique:true,
        required:true
    }

Now, I want to return the users along with all the details of his orders and products in that order.

I tried this but it does not populate the orders with product details:

User.findById(req.user._id)
    .populate("orders")
    .populate("orders.contents.product")

When I try to populate a single Order, it works fine:

Order.findById(req.params.orderId)
    .populate("contents.product")

Solution

  • You can try the nested approach, that in your case should look something like:

    .populate({ 
      path: 'orders',
      populate: {
        path: 'contents.product'
      } 
    })
    

    https://mongoosejs.com/docs/populate.html#populate_multiple_documents