gpt4 book ai didi

node.js - Mongoose 从 `group` 之后的嵌套模式获取属性

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:13 24 4
gpt4 key购买 nike

拥有这个 Mongoose 模式结构:

OrderSchema = new Schema({
name: String,
subtotal: Number,
tax: Number,
date: { type: Date, default: Date.now },
location: { type: ObjectId, ref: 'Location' }
});
...
LocationSchema = new Schema({
name: String
});
...

我正在尝试按位置获取组聚合,但我需要结果中的位置名称。这是聚合命令:

Order.aggregate([
{
$group: {
_id: "$location",
totalSales: {
$sum: "$subtotal"
}
}
}
]).exec(function(err, docs) {
// ...
});

到目前为止,我有这个:

[  
{
"_id":"5572fdc84c98893f0fa3472e",
"result":127.51
},
{
"_id":"5572f4194c98893f0fa3472c",
"result":146.24
},
{
"_id":"5572fdb54c98893f0fa3472d",
"result":183.36
}
]

我正在尝试获取其中的位置名称,如下所示:

[  
{
"_id":"5572fdc84c98893f0fa3472e",
"name": "Location1",
"result":127.51
},
{
"_id":"5572f4194c98893f0fa3472c",
"name": "Location2",
"result":146.24
},
{
"_id":"5572fdb54c98893f0fa3472d",
"name": "Location3",
"result":183.36
}
]

我正在使用 Express。

为了实现这一目标,我需要改变什么?

谢谢

最佳答案

虽然我确信还有其他方法可以做到这一点,但我过去已经通过填充聚合方法生成的 docs 来实现这一点。

这是一个例子:

Order.aggregate([
{
$group: {
_id: "$location",
location: { $first: "$location" },
totalSales: {
$sum: "$subtotal"
}
}
}
]).exec(function(err, docs) {
Order.populate(docs, { path: 'cat', select: '-_id, name' }, function(err, results) {
// here you have the populated results
// I removed the `_id` when populating so it doesn't appear twice
});
});

结果的形状与您在问题中描述的不同,但它至少包含位置的名称。

[  
{
"_id": "5572fdc84c98893f0fa3472e",
"location": { "name": "Location1" },
"result": 127.51
},
{
"_id": "5572f4194c98893f0fa3472c",
"location": { "name": "Location2" },
"result": 146.24
},
{
"_id": "5572fdb54c98893f0fa3472d",
"location": { "name": "Location3" },
"result": 183.36
}
]

关于node.js - Mongoose 从 `group` 之后的嵌套模式获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30688927/

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