Home > database >  how can i get sum of all amounts requested - mongoDB
how can i get sum of all amounts requested - mongoDB

Time:02-24

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

CodePudding user response:

i figured out by my self what i did is to filter through coveredExpense and check if taken amount is greater than the allowed amount

 coveredExpense.filter((expense) => {
    taken = expense.totalTaken;
    emp_id = expense._id;
  });

  if (
    taken >= medicalExpense.allowedAmount &&
    medicalRequesEmployee &&
    medicalRequesEmployee.employee._id.equals(emp_id)
  ) {
    return res.status(400).send("You have exceeded the limit");
  }
  • Related