Untitled
unknown
plain_text
a year ago
1.4 kB
9
Indexable
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
}
}
]);
const data = results?.reduce((result, category) => {
let obj = {};
obj._id = category._id._id;
obj.name = category._id[0][0]?.category;
obj.totalOrders = category.totalOrders;
result.push(obj);
return result;
}, []);
res.status(200).json({
status: 'success',
data: data
});
});Editor is loading...
Leave a Comment