There are two collections. Catalog collection and order Collection. Catalog collection contains seller id , and compelete product details.
Order collection contains order details like ids of ordered products and buyer details.
My problem is how can I get the complete product details when fetching an order .
order collection is given below
Catalog Collection is given below: this is the catalog collection.It contains an array of products. so the products are present there
I need to get product details when fetching order details
CodePudding user response:
const order = await Order.find().populate("products");
CodePudding user response:
I am not sure I understand your question entirely but hope should help you:
Plan
- unwind products
- lookup product with _id of product in
catalog.products
- unwind the lookup result because result of lookup stage is an array
- group this back together
Implementation
const result = await orderModel.aggregate()
.unwind('products')
.lookup({
from: 'catalogs',
let: { product_id: '$products' }, // in order
pipeline: [
{
$unwind: '$products' // $expr cannot digest arrays so we need to unwind which hurts performance...
},
{
$match: { $expr: { $eq: ['$products._id', '$$product_id'] } }
},
{
$project: { _id: 0, products: 1 } // only care products in catelog
}
],
as: 'productDetail'
})
.unwind('productDetail')
.group({
_id: '$_id',
seller: { '$first': '$seller' },
buyer: { '$first': '$buyer' },
products: {
$push: '$productDetail.products'
}
});
However, I don't recommend doing it this way as it can be resource intensive... I suggest you change your database design eg separating product into a separate collection for easier querying.