Home > Software design >  how to populate to an array inside another shema using mongoose
how to populate to an array inside another shema using mongoose

Time:08-27

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

this is the order collection. It contains product Id. I need to get the details of products when fetching orders. Problem is that there is no seperate collection for products. Products are present inside 'catalog' collection

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

  1. unwind products
  2. lookup product with _id of product in catalog.products
  3. unwind the lookup result because result of lookup stage is an array
  4. 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.

  • Related