我如何才能获得所有请求金额的总和-mongoDB



我正在使用MERN堆栈进行人力资源管理项目。我有一个医疗费用部分,员工可以在其中申请费用覆盖(限额=6000(,我如何汇总员工所有申请的金额,并在申请前检查每个员工是否超过限额。这是我的代码:-

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

注意:我尝试了MongoDB聚合,但无法实现目标

我自己想,我所做的是过滤coveredExpense,并检查摄取量是否大于允许的

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");
}

最新更新