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?