0

i need to do some MongoDB queries for return a result for a request. This is my code:

     var getFzAmount = function (req, res, next) {

            var id = req.params.id;
            var total = 0;

            var error = function (err) {
                next(err);
                log.error(err);
            };

            var query = {
                client: id
            };

            ordersRepository.customQuery(db, query, function (orders) {
                _.forEach(orders, function (order) {
                    var query = {order: order._id};
                    billRepository.customQuery(db, query, function (bill) {
                        if (bill) {
                            if (bill.serie = 'FZ') {
                                total += bill.totalWithTaxe;
                            }
                        }
                    }, error);
                });
res.send(total);
            }, error);

        };

First, i get all the "orders" for some query, then, i do a foreach in the orders, for find check if exists document in bills collection for the iterator object position, and if match a condition (object.serie = "FZ"),add to a variable and return it.

As the function inside the _.each its asyncronous res.send function do it before all the queries has finished, what can i do?

colymore
  • 11,776
  • 13
  • 48
  • 90
  • check this link, it may help you: http://stackoverflow.com/questions/17181248/making-mongoose-js-queries-run-synchronously/17296329#17296329 – Harpreet Singh Jul 09 '14 at 13:04
  • one more: http://stackoverflow.com/questions/24185367/mongoose-find-data-by-looping-on-an-array-of-models/24190334#24190334 – Harpreet Singh Jul 09 '14 at 13:05

0 Answers0