【问题标题】:Mongoose: Populate field in collection from other collectionMongoose:填充来自其他集合的集合中的字段
【发布时间】:2016-02-20 02:41:24
【问题描述】:

我有 2 个 Mongoose 集合:ExpenseCategory 和 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);

有一个用 Node.js 编写的 GET api 调用来返回所有 ExpenseCategory items

appRouter.route('/expensecatgories')
  .get(function(req, res){
      ExpenseCategory.find({}, function (expenseCategories) {
        res.json(expenseCategories);
      });
  });

在上面的GET method 中,我想在返回之前在每个expenseCategories 项目中填充字段totalSpentInThisMonth。该字段需要计算为所有expense.amount 的总和,其中expense.expenseCategoryId 匹配expenseCategory.idexpense.date 在当前月份。

如何在返回expenseCategories 之前填充字段totalSpentInThisMonth

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

为此使用聚合框架中的 .aggregate() 方法。您需要首先构造日期以用作日期范围查询的日期在当月内的文档,因此您需要计算 月份日期对象的第一天和最后一天。这些日期将在 $match 管道中用于过滤掉不在当月的文档。

下一个管道流将是 $group 阶段,它按 expenseCategoryId 键对传入文档进行分组,以便您可以使用 累加器运算符 $sum.

下面的代码实现了上面的:

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

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 2015-10-13
    • 2016-05-07
    • 2020-07-11
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多