Nik*_*iya 0 mongoose mongodb node.js mongodb-query mongoose-schema
我正在尝试发送一个总付费和未付费客户端列表以及来自我的节点 API 的数据。在猫鼬方法中,我一直在思考如何走得更远。
任何人都可以建议实现这一目标的最佳方法吗?
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 });
});
});
Run Code Online (Sandbox Code Playgroud)
贷款模式:
const Loan = new Schema({
sName: { type: String },
sPurpose: [String],
sBankName: String,
sBranchName: [String],
nTotalFees: { type: Number },
ePaidunpaid: { type: String ,default:'Unpaid'},
sCashOrCheque: { type: String },
});
Run Code Online (Sandbox Code Playgroud)
结果: 具有付费和未付费客户计数的用户详细信息
[
Paid:{
// Paid users
},
Unpaid:{
// Unpaid Users
},
]
Run Code Online (Sandbox Code Playgroud)
那么在这种情况下,试试这个 -
Loan.aggregate([
{
$group: {
_id: "$ePaidunpaid",
data: { $push: "$$ROOT" },
count: { $sum: 1 }
}
}
]);
Run Code Online (Sandbox Code Playgroud)
输出将是这样的 -
{
"_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
},
Run Code Online (Sandbox Code Playgroud)
解释
流水线的第一级$group组中的所有按文件ePaidunpaid的字段,它只有两个值Paid或Unpaid因此分别渲染只有两个文件。
下一步是积累被分组在一起的原始数据(文档)。这是通过$push在数据字段上使用累加器实现的,推送$$ROOT有效地引用了当前正在由流水线阶段处理的文档。
由于您需要计算所有付费和未付费用户,因此需要一个$sum累加器来计算每个组中的所有项目。
| 归档时间: |
|
| 查看次数: |
3186 次 |
| 最近记录: |