在hooks for get请求之前在FeatherJS中进行聚合排序



我需要帮助如何为get请求聚合排序。

我想用FeatherJS和MongoDD构建一个web API。web api将有以下食物菜单项的样本数据集(见下文)。

样本数据集

[
{
_id: 1,
name: "Pizza",
price: 10,
expirydate: ISODate("2022-06-01T00:00:00Z")
},
{
_id: 2,
name: "Chicken Burger",
price: 5,
expirydate: ISODate("2022-04-01T00:00:00Z")
},
{
_id: 3,
name: "Pasta Salad",
price: 0,
expirydate: ISODate("2022-05-01T00:00:00Z")
},
{
_id: 4,
name: "Veg Sandwich",
price: 8,
expirydate: ISODate("2022-03-01T00:00:00Z")
},
{
_id: 5,
name: "Beef Burger",
price: 5,
expirydate: ISODate("2022-12-12T00:00:00Z")
},
{
_id: 6,
name: "Fruit Sandwich",
price: 8,
expirydate: ISODate("2022-04-02T00:00:00Z")
},
{
_id: 7,
name: "Pork Burger",
price: 5,
expirydate: ISODate("2022-07-21T00:00:00Z")
},
{
_id: 8,
name: "Potato Salad",
price: 0,
expirydate: ISODate("2022-08-01T00:00:00Z")
},
{
_id: 9,
name: "Fruit Salad",
price: 0,
expirydate: ISODate("2022-01-01T00:00:00Z")
}
]

排序需要在我的前端从我的api发出HTTP Get请求之前,我想对它进行排序。为了做到这一点,使用featherjs,我为find创建了一个before钩子,允许我预处理/排序我的数据集。

我想要排序的方式是首先将项目分为2组,price = 0和price != 0。之后,我希望组内的记录按到期日期(升序)排序。之后,我想将两个组连接在一起,其中第一个组是price != 0,第二个组要连接到它的末端。

最终结果将是非零价格首先出现,并按到期日升序排序。之后,将出现价格为零的商品,并按到期日升序排序。就像我下面提供的。

排序后的数据集

[  
{
name: "Veg Sandwich",
price: 8,
expirydate: ISODate("2022-03-01T00:00:00Z")  
},  
{
name: "Chicken Burger",
price: 5,    
expirydate: ISODate("2022-04-01T00:00:00Z")
},  
{    
name: "Fruit Sandwich",
price: 8,
expirydate: ISODate("2022-04-02T00:00:00Z")  
},  
{    
name: "Pizza",    
price: 10,    
expirydate: ISODate("2022-06-01T00:00:00Z")  
},  
{    
name: "Pork Burger",    
price: 5,   
expirydate: ISODate("2022-07-21T00:00:00Z")  
},  
{    
name: "Beef Burger",    
price: 5,    
expirydate: ISODate("2022-12-12T00:00:00Z")  
}, 
{
name: "Fruit Salad",    
price: 0,    
expirydate: ISODate("2022-01-01T00:00:00Z")  
},  
{    
name: "Pasta Salad",    
price: 0,    
expirydate: ISODate("2022-05-01T00:00:00Z")  
},  
{    
name: "Potato Salad",    
price: 0,    
expirydate: ISODate("2022-08-01T00:00:00Z")  
}
]

问题:我如何为find (get)编写我的before钩子,以便数据集可以像上面一样排序。

我该怎么做在制品,不确定是否下面的代码将工作。前钩

db.food.aggregate([
{ $sort: { price: -1, expirydate: 1 } },
])

我已经通过聚合排序得到了答案。聚合排序意味着数据库操作按称为阶段的顺序执行。为了在我的问题中实现这一点,请在下面找到我的代码的更多细节。

Stage1:按过期日期对所有食品进行分类

Stage2:设置一个条件,将免费食品(price = $0)推入免费组,否则推入非免费组。由于食品已按到期日升序排列,该组中的食品也将按该顺序排列。

Stage3:为了使非自由组排在前面,按降序排序。

db.items.aggregate([
{
$sort: { expirydate: 1 }
},
{
$group: {
_id: {
$cond: {
if: { $eq: ["$price", 0] },
then: "free",
else: "notFree"
}
},
fooditems: { $push: "$$ROOT" }
}
},
{
$sort: { $_id: -1 }
},
{
$project: {
_id: 0,
items: {
$concatArrays: ["$items"]
}
}
},
{
$unwind: "$items"
},
)];

最新更新