Amend results from two collections into an array using _.each() Amend results from two collections into an array using _.each() mongoose mongoose

Amend results from two collections into an array using _.each()


You are not waiting for you second call to finish, so you don't have all data at hand. Your return statement does not work as you think it will.

You should read a bit about asynchronicity in JavaScript :)

This code should work. Please take some time to study it and understand why. The trySend function acts as a simple synchronizer and only responds when all data is available. This is not the best way to do it - only the simplest.

app.get('/bills', function( req, res ) {  Bills.find({type: bill_type}, function( err, bills ) {    if( err ) return res.send(err);    var tries = 0;    var details = { bills: bills };    var trySend = function (){      tries++;      if (tries === bills.length) {        res.send(details);        }    };    bills.forEach( function ( bill ) {      Transactions.find({billId : bill._id}, function ( err, transactions ) {        if ( err ) return res.send( err );        bill.transations = transactions;        trySend();      });      });          });});