mongoose在`group`之后从嵌套模式获取属性
有这个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 }); });
结果的形状与您在问题中描述的内容不完全相同,但至less包含该位置的名称。
[ { "_id": "5572fdc84c98893f0fa3472e", "location": { "name": "Location1" }, "result": 127.51 }, { "_id": "5572f4194c98893f0fa3472c", "location": { "name": "Location2" }, "result": 146.24 }, { "_id": "5572fdb54c98893f0fa3472d", "location": { "name": "Location3" }, "result": 183.36 } ]
- 让快递服务器接受CORS请求
- HTML不在Jade中渲染
- 如何在res.send之后但在响应离开服务器之前挂钩==>当res.statusCode被知道时
- 如何在特定的path前缀上安装app.get()路由
- 为什么expressjs每个OPTIONS响应都发送Set-Cookie头?
- expression3.0如何使用app.locals.use和res.locals.use
- TypeError:对象函数(req,res,next){app.handle(req,res,next); }没有方法“configuration”
- 服务favicon npm包不与快递工作
- 在testingnodeJS应用程序时,应该如何设置Capybara.app?