I have a mongoose model circuit created with something like the following.
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);
}
};
Now I want to grab a collection of orders, but I would like to include "totalInvoiced" and "totalDiscount" as an additional property for each document in the returned collection. I understand that this may be the case when "totalInvoiced" is a virtual property, but I do not always want it to be included. This is how I tried it, but I feel that is probably the best way to do this.
Order.find({}, function (err, orders) {
_.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;
});
- , , . , querystream