pete
pete

Reputation: 2799

Is it possible to populate nested references in Mongoose?

I'm new to MongoDB, trying to populate data from another collection into a response. The simplest example would be as follows:

const CartSchema = new Schema({
  items: [{
    product: { type: Schema.Types.ObjectId, ref: 'product' },
    qty: Number
  }],
  ...
});

I'm able to use .populate() when the relationships are at the root level, but in the above example, I have an array of items with their own properties, e.g. qty, plus an _id reference to a product. I would like to populate the product object into each car item, but can't seem to find any examples on what's the "right" way to do it.

Cart.findById(id)
  .populate('products')   // <-- something like this
  .then(record => ... )
  .catch(next);

I know that I could probably do a separate .find() on the products collection after locating the cart record and manually extend the initial object, but I was hoping there was a way to populate the data within the original query?

Upvotes: 1

Views: 1877

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

You can try this, it will work for you.

Cart.findById(id)
    .populate('items.product')
    .then(record => ... )
    .catch(next);

.populate('items.product') will populate the product object of all the cart item present in the array.

Upvotes: 3

Related Questions