Untitled

mail@pastecode.io avatar
unknown
plain_text
8 days ago
1.1 kB
4
Indexable
Never
exports.getOrdersByCategories = catchAsync(async (req, res, next) => {
  let filter = {};
  filter.isvalid = true
  if (req.user?.role == 'salesman') {
    filter.sales_man = req.user.profile;
  }
  const results = await Order.aggregate([
    { $match: filter },
    { $unwind: '$products' },
    {
      $lookup: {
        from: 'products',
        localField: 'products.product',
        foreignField: '_id',
        pipeline: [
          {
            $lookup: {
              from: 'categories',
              localField: 'categories',
              foreignField: '_id',
              pipeline: [{ $project: { category: 1 } }],
              as: 'category'
            }
          }

          // { $project: { categories: 1} },
          //   { $unwind : '$category'},
        ],
        as: 'products.product'
      }
    },
    {
      $group: {
        _id: '$products.product.category', // Grouping by category
        totalOrders: { $sum: '$products.quantity' } // Counting the orders in each category
      }
    } 
  ]);
Leave a Comment