'how can i get sum of all amounts requested - mongoDB

I am working on an HRM project using MERN stack I have a medical expense section in which employees can request expense coverage (limit = 6000), how can I sum all requested amounts by employee and check if each employee is exceeding the limit before requesting here is my code:-

router.post("/", async (req, res) => {
  // check if employee has pending  request 
  let medicalExpenseRequest = await MedicalExpenseRequest.findOne({
    "employee._id": req.body.employeeId,
    "medicalExpense._id": req.body.medicalExpenseId,
    status: "Pending",
  });
  if (medicalExpenseRequest)
    return res
      .status(400)
      .send("Oops there is pending medical request for this employee!");
  // this blocks the employee to request more than the limit at once // medicalexpense.allowed == 6000
  if (req.body.amount > medicalExpense.allowedAmount)
    return res
      .status(400)
      .send(
        `Sorry can't request more than ${medicalExpense.allowedAmount} ETB`
      );

  // keep track of each employee request 
//I want to check if the sum of all amounts requested by employee is greater than the limit and block if it is true
  let taken;

  const coveredExpense = await MedicalExpenseRequest.aggregate([
    // { $match: { _id: { $eq: req.body.employeeId } } },
    {
      $group: {
        _id: "$employee._id",
        totalTaken: { $sum: "$amount" },
      },
    },
  ]);
  

  // process the request successfully

});

NB: I tried MongoDB aggregates but I could not able to achieve the target



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source