Mongodb Mongoose:从其他集合填充集合中的字段

Mongodb Mongoose:从其他集合填充集合中的字段,mongodb,mongoose,Mongodb,Mongoose,我有两个猫鼬收藏:ExpenseCompute和Expense var ExpenseCategorySchema = new Schema({ name: String, totalSpentInThisMonth: Number }); mongoose.model('ExpenseCategory', ExpenseCategorySchema); var ExpenseSchema = new Schema({ expenseCategoryId: {type:

我有两个猫鼬收藏:ExpenseCompute和Expense

var ExpenseCategorySchema = new Schema({
    name: String,
    totalSpentInThisMonth: Number
});
mongoose.model('ExpenseCategory', ExpenseCategorySchema);

var ExpenseSchema = new Schema({
    expenseCategoryId: {type: Schema.Types.ObjectId, ref: 'ExpenseCategory'},
    amount: Number,
    date: Date
});
mongoose.model('Expense', ExpenseSchema);
有一个
GET-api
调用编写在Node.js中,用于返回所有
ExpenseCategory项目

appRouter.route('/expensecatgories')
  .get(function(req, res){
      ExpenseCategory.find({}, function (expenseCategories) {
        res.json(expenseCategories);
      });
  });
在上面的
GET方法中
返回之前,我想在每个
支出类别
项目中填充字段
totalspentisthismount
。此字段需要计算为所有
费用。金额
的总和,其中
费用。费用类别id
费用类别id
匹配,并且
费用。日期
在当月

在返回
费用类别之前,如何填充字段
totalSpentInThisMonth

为此使用聚合框架中的方法。您需要首先构造日期,将其用作日期在当前月份内的文档的日期范围查询,因此需要计算 月份日期对象的第一天和最后一天。这些日期将在管道中用于筛选不在当前月份的文档

下一个管道流将是阶段,该阶段通过
expenseCategoryId
键对传入文档进行分组,以便您可以使用 累加器运算符

以下代码实现了上述功能:

appRouter.route('/expensecatgories').get(function(req, res){
    var today = new Date(), y = today.getFullYear(), m = today.getMonth();
    var firstDay = new Date(y, m, 1);
    var lastDay = new Date(y, m + 1, 0);
    var pipeline = [
        {
            "$match": {
                "date": { "$gte": firstDay, "$lt": lastDay }
            }
        },
        {
            "$group": {
                "_id": "$expenseCategoryId",
                "totalSpentInThisMonth": { "$sum": "$amount" }
            }
        }
    ];

    Expense.aggregate(pipeline, function (err, result){     
        if (err) throw err;
        var categories = result.map(function(doc) { return new ExpenseCategory(doc) });
        Expense.populate(categories, { "path": "expenseCategoryId" }, function(err, results) {
            if (err) throw err;
            console.log(JSON.stringify(results, undefined, 4 ));
            res.json(results);
        });
    });        
});
可能重复的