node.js 在猫鼬中填充 + 聚合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32789053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populate + Aggregate in Mongoose
提问by Guilherme
I have two Mongoose models: one for transactions and the other one for the tags associated with them. In order to implement some reports, I need aggregate code like this:
我有两个 Mongoose 模型:一个用于交易,另一个用于与它们相关的标签。为了实现一些报告,我需要这样的聚合代码:
Transaction.aggregate([
{ $unwind: '$tags' },
{
$group: {
_id: '$tags',
amount: {
$sum: '$amount'
}
}
}
])
Question
题
This produces output containing _idand amount. Now, I'd like to populate the other fields (e.g. name) from the model, keeping the calculated amountcolumn. Can I do that within a simple populate?
这将产生包含_id和 的输出amount。现在,我想填充模型中的其他字段(例如name),同时保留计算amount列。我可以在一个简单的内做到这一点populate吗?
Edit
编辑
The schemas for the models I'm describing:
我所描述的模型的模式:
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
}
});
回答by Thomas Bormans
You can populate an aggregation after you fetched the data from the MongoDB. This will look something like this:
从 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
});
});

