1

I have been trying to populate products in my Cart. My Cart model is -

const ProductSchema = new mongoose.Schema({
  product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product'},
  quantity: Number
});
const CartSchema = new mongoose.Schema({
  userId: mongoose.Schema.Types.ObjectId,
  products: [ProductSchema]
});

I am trying to get the cart value like this -

let getCart = async (userId) => {
  let res = await Cart.find({ userId: userId }).populate('products.product')
  return res;
};

Output -

{
  userId: xyz,
  products:[
    product: null,
    quantity:1
  ]
}

Expected Result -

{ 
  userId: xyz,
  products:[
    product: {
      name: 'product name', 
      description:'',
      ...
    },
    quantity:1
  ]
}
Towkir
  • 3,889
  • 2
  • 22
  • 41
Komal Bansal
  • 789
  • 2
  • 7
  • 20
  • Possible duplicate of [Mongoose populating array of subdocuments](https://stackoverflow.com/questions/40470823/mongoose-populating-array-of-subdocuments) – Vikash_Singh May 16 '19 at 19:20

2 Answers2

0

You need to populate only products and select product to show from the populated array.

Shivam Pandey
  • 3,756
  • 2
  • 19
  • 26
-1

Just populating product is enough I guess.

let getCart = async (userId) => {
  let res = await Cart.find({ userId: userId }).populate('products')
  return res;
};