我正在尝试从我的 Node API 发送一份已付费和未付费客户总数的列表,其中包含计数以及数据。 在 Mongoose 方法中,我一直在思考如何走得更远。
有人可以建议实现这一目标的最佳方法吗?
router.get("/", ensureAuthenticated, (req, res) => {
Loan.aggregate([
{
$match: {
ePaidunpaid: "Unpaid"
}
}
]).then(function(data) {
console.log(data);
res.render("dashboard", { admin: req.user.eUserType, user: req.user,data:data });
});
});
贷款模式:
const Loan = new Schema({
sName: { type: String },
sPurpose: [String],
sBankName: String,
sBranchName: [String],
nTotalFees: { type: Number },
ePaidunpaid: { type: String ,default:'Unpaid'},
sCashOrCheque: { type: String },
});
结果: 用户的详细信息以及付费和未付费客户的数量
[
Paid:{
// Paid users
},
Unpaid:{
// Unpaid Users
},
]
最佳答案
那么,在这种情况下,试试这个 -
Loan.aggregate([
{
$group: {
_id: "$ePaidunpaid",
data: { $push: "$$ROOT" },
count: { $sum: 1 }
}
}
]);
输出会是这样的 -
{
"_id": "Paid",
"data": [
// All the documents having ePaidunpaid = Paid
{ _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields },
{ _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields }
],
count: 2
},
{
"_id": "Unpaid",
"data": [
// All the documents of having ePaidunpaid = Unpaid
{ _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields },
{ _id: "asdasd123 1eqdsada", sName: "Some name", // Rest of the fields }
],
count: 2
},
说明
管道的第一阶段$group
根据ePaidunpaid
字段对所有文档进行分组,该字段只有两个值Paid
或Unpaid
,从而分别渲染两个文档。
下一步是积累原始数据(文档)并分组在一起。这是通过在数据字段上使用 $push
累加器,推送 $$ROOT
来实现的,它有效地引用了管道阶段当前正在处理的文档。
由于您需要计算所有付费和未付费用户的数量,因此需要使用 $sum
累加器来计算每个组中的所有项目。
关于node.js - Mongoose 聚合、匹配、计数、分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49710285/