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
  ]
}
1

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

-1

Just populating product is enough I guess.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.