[英]populate nested array of objects mongoose
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
]
}
您只需要填充products
然后从填充的阵列中选择要显示的product
即可。
Just populating product is enough I guess. 我猜仅仅填充产品就足够了。
let getCart = async (userId) => {
let res = await Cart.find({ userId: userId }).populate('products')
return res;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.