我如何从卖家那里得到所有的订单,然后按以前的日期到现在对它们进行排序?
这是我在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
我尝试了下面的代码,但收到了一个空数组
这是我的URL
您的位置:首页〉〉〉
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中的对象ID属于产品数组中的sellerId**。**
1条答案
按热度按时间lyr7nygr1#
您可以将
$match
步骤更改为:因为当前您正在查找字段
id
,但您希望查找字段sellerId
。了解它在playground example上的工作原理