如何为在mongoose查询中返回的每个文档执行asynchronous方法

我有一个像下面这样的东西设置mongoose模型模式。

var orderSchema = new Schema ({ _invoices: [{ type: Schema.ObjectId, ref: 'invoice'}, _discounts: [{ type: Schema.ObjectId, ref: 'discount'}, _client: String }); orderSchema.methods.totalInvoiced = function (cb) { this.populate('_invoices', function (err, order) { cb(err, _.reduce(_.pluck(order._invoices, 'amount'), function (a, b) { return a+b; }, 0); } }; orderSchema.methods.totalDiscount = function (cb) { this.populate('_discounts', function (err, order) { cb(err, _.reduce(_.pluck(order.discounts, 'amount'), function (a, b) { return a+b; }, 0); } }; 

现在我想要获取订单集合,但是我希望在返回的集合中的每个文档中包含“totalInvoiced”和“totalDiscount”作为附加属性。 我知道这可能是“totalInvoiced”是一个虚拟财产,但我并不总是希望它被包括在内。 这是我如何尝试,但我觉得可能有更好的方法来做到这一点。

 Order.find({}, function (err, orders) { // for each order calc totals and add to document as two new properties _.each(orders, function (order) { async.parallel({ invoice: function (cb) { order.totalInvoiced(cb); }, discount: function (cb) { order.totalDiscount(cb); } }, function (err, result) { order.totalInvoiced = result.invoice; order.totalDiscount = result.discount; } }); return orders; }); 

我的问题是什么是最好的方式来执行一个集合的查询,但也作为查询的一部分,在每个文档执行一些asynchronous方法,或者是我通过迭代查询的结果正确的方式来做到这一点做这个。 也许用一个查询stream

_.each()不是asynchronous的,所以当所有的总数都被填充时,你将很难继续执行。 此外,如果您无法控制Order.find()返回的订单Order.find() ,则可以通过不限制数量限制来获得一些严重的性能问题。

你可以尝试这样的事情:

 Order.find({}, function (err, orders) { // populate max 15 orders at any time async.mapLimit(orders, 15, function (order, cb) { async.parallel({ invoice: function (cb) { order.totalInvoiced(cb); }, discount: function (cb) { order.totalDiscount(cb); } }, function (err, result) { order.totalInvoiced = result.invoice; order.totalDiscount = result.discount; return cb(null, order); }); }, function (err, orders) { console.log('Done!'); }); });