我怎樣才能從賣家那里得到所有的訂單,然后按前一個日期到現在排序?
這是我在 Order.find() 時得到的所有交易,
[
{
"_id": "636357777877c919bb2cfa45",
"products": [
{
"productId": "636355a07877c919bb2cdfdc",
"quantity": 1,
"sellerId": "636355187877c919bb2cdf1f",
"_id": "636357777877c919bb2cfa46"
}
],
"amount": 100,
"createdAt": "2022-10-03T05:53:59.997Z",
},
{
"_id": "636357da7877c919bb2d035f",
"products": [
{
"productId": "636357387877c919bb2cf494",
"quantity": 1,
"sellerId": "636355187877c919bb2cdf1f",
"_id": "636357da7877c919bb2d0360"
}
],
"amount": 100,
"createdAt": "2022-11-03T05:55:38.858Z",
"updatedAt": "2022-11-03T05:55:38.858Z",
"__v": 0
},
{
"_id": "636367d2407816df5f589bc6",
"products": [
{
"productId": "63635acf7877c919bb2d3d95",
"quantity": 1,
"sellerId": "636355187877c919bb2cdf1f",
"_id": "636367d2407816df5f589bc7"
}
],
"amount": 20,
"createdAt": "2022-11-03T07:03:46.350Z",
}
]
所以我想在這里得到的是某個月份賣家的總金額。例如,我這里有 3 個訂單,其中一個是 10 月的,另外兩個是 11 月的。
所以輸出應該是。
October = 100
November = 120
我嘗試了下面的代碼,但我收到了一個空陣列
這是我的網址
http://localhost:5000/api/order/previousSales/636355187877c919bb2cdf1f
router.get('/previousSales/:id', async (req,res) => {
const {id} = req.params
const date = new Date();
const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));
try {
const order = await Order.aggregate([
{
$match: {
createdAt: {gte: previousMonth}, ...(id && {
products: {$elemMatch: {id}}
})
}
},
{
$project: {
month: { $month: "$createdAt" },
sales: "$amount",
},
},
{
$group: {
_id: "$month",
total: { $sum: "$sales" },
},
},
])
res.status(200).json(order)
} catch (error) {
res.status(400).json({message: error.message})
}
})
編輯
我忘了提到 URL 中的 Object Id 屬于product 陣列中的SellerId 。
uj5u.com熱心網友回復:
您可以將$match步驟更改為:
{$match: {
createdAt: {$gte: previousMonth},
products: {$elemMatch: {sellerId: id}}
}},
由于目前您正在尋找該領域id,但您想尋找該領域sellerId。
看看它在操場上的例子是如何作業的
uj5u.com熱心網友回復:
嘗試將您的查詢更改為:
const matchId = id ? { 'products._id': id } : { 'products._id': { $ne: undefined } }
const order = await Order.aggregate([
{
$match: {
createdAt: {
$gte: previousMonth.toISOString(),
},
matchId
},
},
{
$project: {
month: {
$month: {
$dateFromString: {
dateString: '$createdAt',
},
},
},
sales: '$amount',
},
},
{
$group: {
_id: '$month',
total: {
$sum: '$sales',
},
},
},
]);
鏈接到游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526576.html
