mongoose在`group`之后从嵌套模式获取属性

时间:2015-06-07 00:39:22

标签: node.js mongodb express mongoose

拥有这个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。

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

谢谢

1 个答案:

答案 0 :(得分:2)

虽然我确信还有其他方法可以做到这一点,但我过去通过填充聚合方法产生的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
   }
]