在Mongoose中填充+聚合

时间:2015-09-25 19:07:45

标签: node.js mongodb mongoose

我有两个Mongoose模型:一个用于事务,另一个用于与之关联的标记。为了实现一些报告,我需要这样的汇总代码:

Transaction.aggregate([
  { $unwind: '$tags' },
  {
    $group: {
      _id: '$tags',
      amount: {
        $sum: '$amount'
      }
    }
  }
])

问题

这会生成包含_idamount的输出。现在,我想从模型中填充其他字段(例如name),并保留计算出的amount列。我可以在简单的populate内完成吗?

修改

我所描述的模型的模式:

var TransactionSchema = new Schema({
  description: {
    type: String,
    trim: true
  },
  amount: {
    type: Number,
    required: 'Forneça um valor',
  },
  date: {
    type: Date,
    required: 'Forneça uma data',
    default: Date.now
  },
  fromOfx: {
    type: Boolean,
    default: false
  },
  created: {
    type: Date,
    default: Date.now
  },
  correlated: {
    type: Boolean,
    default: false
  },
  tags: [{
    type: Schema.Types.ObjectId,
    ref: 'TransactionTag'
  }],
  correlates: [{
    type: Schema.Types.ObjectId,
    ref: 'Transaction'
  }],
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

var TransactionTagSchema = new Schema({
  name: {
    type: String,
    required: 'Forneça um nome',
    trim: true
  },
  description: {
    type: String,
    trim: true
  },
  amount: {
    type: Number
  }
});

1 个答案:

答案 0 :(得分:25)

您可以在从MongoDB获取数据后填充聚合。这看起来像这样:

// Your aggregate query from your question
Transaction.aggregate([{
                            $unwind: '$tags'
                        }, {
                            $group: {
                                _id: '$tags',
                                amount: {
                                    $sum: '$amount'
                                }
                            }
                        }])
    .exec(function(err, transactions) {
        // Don't forget your error handling
        // The callback with your transactions
        // Assuming you are having a Tag model
        Tag.populate(transactions, {path: '_id'}, function(err, populatedTransactions) {
            // Your populated translactions are inside populatedTransactions
        });
    });