【问题标题】:Where to process data on MERN stack?在哪里处理 MERN 堆栈上的数据?
【发布时间】:2020-09-18 06:17:33
【问题描述】:

我正在构建一个基于 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 }
    }
   ]
  }
}

【问题讨论】:

    标签: javascript node.js mongodb mongoose mern


    【解决方案1】:

    您应该让 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
                }
            }
    
        ])
    

    然后使用节点返回结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2021-07-27
      • 2022-12-14
      • 2021-02-24
      • 2014-04-21
      • 2011-11-09
      相关资源
      最近更新 更多