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 } ]
- Krakenjs如何将除api调用之外的所有请求路由到index.html?
- 使用茉莉花来testingExpress.js
- 在Node.js中使用远程图像来dynamic生成PDF
- 快线不回来
- 在node.jsexpression式中,对“/ locations / search”的请求总是进入“/ locations /:location_id”,如何以正确的方式进行路由
- Node.js + Express 4 + Passport.js如何获取当前login的所有用户列表?
- Express JS 4.0命令行工具不起作用
- 我如何提供index.jade?
- 节点JS / Express渲染html,然后下载一个文件相同的GET请求