我设置了一个猫鼬模型架构,如下所示。
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;
});
我的问题是,执行查询集合的最佳方法是什么,还要在每个文档上执行一些异步方法作为查询的一部分,还是通过迭代查询结果的正确方法来实现此目的?做这个。也许与查询流
_.each()
不是异步的,因此当填充所有总数时,您将很难继续执行。另外,如果您无法控制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!');
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句