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

       

网上收集的解决方案 "在Mongoose中填充+聚合"

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