Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 2x 2x 2x | import { userDefaultProjection } from "../../CONSTANT/projections.js";
import OrdersModel from "../../models/Orders.js";
export default async function topCustomers(limit = 5) {
try {
const customers = await OrdersModel.aggregate([
{
$group: {
_id: "$userId",
totalSpending: { $sum: "$totalPrice" },
totalOrders: { $count: {} }
}
},
{ $sort: { totalSpending: -1, totalOrders: -1 } },
{ $limit: +limit },
{
$lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "userData",
pipeline: [{ $project: { ...userDefaultProjection, _id: 0 } }]
}
},
{
$project: {
_id: 1,
totalSpending: 1,
totalOrders: 1,
userData: { $first: "$userData" }
}
}
])
return customers;
} catch (error) {
console.log(error)
return null;
}
}
|