Where to process data on MERN stack?

Viewed 95

I'm building an expenses control app based on MERN Stack and I was wondering which way is the best to process data.

To be more specific, my expense data has the following model

  {
    "_id" : ObjectId("5eceb10f0b59a200a545c39b"),
    "date" : ISODate("2019-10-10T00:00:00.000Z"),
    "description" : "INTERT BILL",
    "credit" : "",
    "debit" : "-100",
    "category" : "HOME",
    "subcategory" : "INTERNET",
    "__v" : 0
  }

If I want to group expenses by category on a specific date, what would be the best way to do it?

Processing it on mongodb, through an aggregate query or fetch all expenses on a specific date range and grouping it on node.js before sending to client?

Desired output:

{
  HOME: {
   total: '-300',
   subcategories: [
    {
      internet: { total: -100}
    },
    {
      water: { total: -200 }
    }
   ]
  }
}

1 Answers

You should let MongoDB to the grouping, especially if you're dealing with a big dataset. The reason for that is that you could potentially block the event-loop by long running operations. Here's an aggregation query that should help you get started:

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
            }
        }

    ])

and just return the result using node.

Related