gpt4 book ai didi

node.js - 在 Mongoose 中填充 + 聚合

转载 作者:IT老高 更新时间:2023-10-28 13:12:49 26 4
gpt4 key购买 nike

我有两个 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
}
});

最佳答案

您可以在从 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
});
});

关于node.js - 在 Mongoose 中填充 + 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com