在 MERN 堆栈上的何处处理数据?
Where to process data on MERN stack?
我正在构建一个基于 MERN Stack 的费用控制应用程序,我想知道哪种方式是处理数据的最佳方式。
更具体地说,我的费用数据有以下模型
{
"_id" : ObjectId("5eceb10f0b59a200a545c39b"),
"date" : ISODate("2019-10-10T00:00:00.000Z"),
"description" : "INTERT BILL",
"credit" : "",
"debit" : "-100",
"category" : "HOME",
"subcategory" : "INTERNET",
"__v" : 0
}
如果我想在特定日期按类别对费用进行分组,最好的方法是什么?
在 mongodb 处理它,通过聚合查询或获取特定日期范围内的所有费用并在发送给客户之前在 node.js 对其进行分组?
期望的输出:
{
HOME: {
total: '-300',
subcategories: [
{
internet: { total: -100}
},
{
water: { total: -200 }
}
]
}
}
您应该让 MongoDB 进行分组,尤其是在处理大型数据集时。这样做的原因是您可能 block the event-loop 通过长 运行 操作。这是一个可以帮助您入门的聚合查询:
yourModel.aggregate([
{
$match: {
date: yourDateToMatch
}
},
{ // you need this conversion stage in order to be able to do maths with your debit field
$addFields: {
convertedDebit: {
$toDecimal: "$debit"
}
}
},
{
$group: {
_id: "$category",
total: {
$sum: "$convertedDebit"
},
// add grouping options for subcategories
}
}
])
并且只是 return 使用节点的结果。
我正在构建一个基于 MERN Stack 的费用控制应用程序,我想知道哪种方式是处理数据的最佳方式。
更具体地说,我的费用数据有以下模型
{
"_id" : ObjectId("5eceb10f0b59a200a545c39b"),
"date" : ISODate("2019-10-10T00:00:00.000Z"),
"description" : "INTERT BILL",
"credit" : "",
"debit" : "-100",
"category" : "HOME",
"subcategory" : "INTERNET",
"__v" : 0
}
如果我想在特定日期按类别对费用进行分组,最好的方法是什么?
在 mongodb 处理它,通过聚合查询或获取特定日期范围内的所有费用并在发送给客户之前在 node.js 对其进行分组?
期望的输出:
{
HOME: {
total: '-300',
subcategories: [
{
internet: { total: -100}
},
{
water: { total: -200 }
}
]
}
}
您应该让 MongoDB 进行分组,尤其是在处理大型数据集时。这样做的原因是您可能 block the event-loop 通过长 运行 操作。这是一个可以帮助您入门的聚合查询:
yourModel.aggregate([
{
$match: {
date: yourDateToMatch
}
},
{ // you need this conversion stage in order to be able to do maths with your debit field
$addFields: {
convertedDebit: {
$toDecimal: "$debit"
}
}
},
{
$group: {
_id: "$category",
total: {
$sum: "$convertedDebit"
},
// add grouping options for subcategories
}
}
])
并且只是 return 使用节点的结果。