【发布时间】:2019-03-27 10:58:40
【问题描述】:
我有这个猫鼬方法/查询,它可以从某个用户那里找到所有“收入”,但前提是“收入”的日期在当月之内。
代码:
module.exports.getMonthlyIncome = function(userId, callback){
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate();
const start = new Date(year, month, 1);
const end = new Date(year, month, 30);
Income.find({owner: userId, date: { $gte: start, $lt: end }}, callback);
}
结果:
[
{
"_id": "58cc9ee50fe27e0d2ced5193",
"amount": 600,
"description": "Ripco Salary",
"owner": "58cc9e950fe27e0d2ced5192",
"__v": 0,
"date": "2017-03-17T00:00:00.000Z"
},
{
"_id": "58ccc3cfca6ea10980480d42",
"amount": 450,
"description": "Another Ripped co salary",
"owner": "58cc9e950fe27e0d2ced5192",
"__v": 0,
"date": "2017-03-26T00:00:00.000Z"
}
]
结果如预期,给了我一个月内属于某个用户的2份收入文件。
现在,我想从这些文档中获取每个“金额”字段的总和。
所以在这种情况下,总和是 1050。
我将如何在 Mongoose 中实现这一点?
非常感谢任何帮助,干杯。
【问题讨论】: