Problem
I have 3 collections in MongoDB
- regions
- each document corresponds to one geographical region, has a field for the region name, and another field which is an array of farms within the broader region
- details
- this collection contains documents, each one relating to a particular farm, and with various fields relating to details of that farm, e.g. number of cows
- yield
- this collection again contains documents where each one relates to a particular farm, and the fields in this instance are for farm output per day
I am trying to write a function that will start with the regions collection, for the first region it then takes each individual farm ID, and uses this to query the other two collections getting the total yield and total number of cows for that farm, then summing for each farm to get a total for the region.
Attempt
I first tried using straightforward mongodb calls for just a single region
var db = client.connect('mongodb://localhost:27017/mydb', function(err,db) {
if (err) throw err;
var regions = db.collection('Regions');
var details = db.collection('Details');
var yield = db.collection('Yield');
regions.find({"region" : "Gotham"}).toArray(function(err, docs) {
for (var k = 0; k < docs.length; k++) {
var regionYield = 0;
for (var j = 0; j < docs[k].farms.length; j++) {
var farmYield = 0;
var farmID = docs[k].farms[j]
yield.find({Farm_ID: farmID}).toArray(function(err, docs) {
for (var i = 0; i < docs.length; i++) {
farmYield += +docs[i].Yield;
}
console.log('finished inner loop');
regionYield += farmYield;
});
}
console.log('finished middle loop');
}
console.log('finished outer loop');
});
After the completion of the outer loop I want to do something with the final regionYield
value, but as it is structured now, the outer loop finishes before the necessary computation is finished in the inner loop, due to the async mongo call. I just can't figure out to get around this. I have looked at a lot of questions/answers here explaining callbacks but I just can't figure out how to apply it to my case.