I cannot find a way to get my find function to work. I would like to find all billIds from the bills collection and then check for each billId inside the transaction DB.
The problem is, because of the aSynch - I reckon, the id doesn't update on my loop. Here is the code:
Bills.find({type: bill_type, endDate: {"$gte" : new Date(year + "-" + month + "-1")}}).find(function(err, bills){
        if(err)
            res.send(err);
        details.bills = bills;
        for(key in bills){
            var billId = bills[key]._id;
            console.log("BillId: " + billId); // Here the ids are unique (which is what I want)
             Transactions.find({billId : billId}, function(err, transactions){
                if (err) {
                    console.log('error: '+ err)
                } else {
                    console.log("Transaction BillId: " + billId); // Here I get always the same ID - which is not quiet what I need.
                }
            });
            //console.log(transactions);
        }
       res.send(details);  
    });
There result at the console is:
BillId: 549bf0597886c3763e000001
BillId: 54a014bfac01ca3526000001
BillId: 54a015753547a6c026000001
^ Good result - Comes from the first console.log inside the for().
and then:
Transaction BillId: 54a015753547a6c026000001
Transaction BillId: 54a015753547a6c026000001
Transaction BillId: 54a015753547a6c026000001
^ Bad result - Its repeating the last result from the for() and I need all results.
At the first console.log(), when I get the results from the first find() (Bills.find()), I can see all the ids on the log but when I try to get them inside the second Find (Transactions.find()), they repeat the last id.
So in this current state I am not able to query the db for each id. Any help on this is appreciated.
Please let me know if you need any clarification.
Thanks in advance!
 
     
     
    