How to execute asynchronous methods for each document returned in a mongoose request

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) {
     // 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;

    });

- , , . , querystream

+4
1

_.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!');
    });
});
+1

Source: https://habr.com/ru/post/1539576/


All Articles