title: Nested loops with async mongodb queries in node
body: <h1>Problem</h1>
  
  <p>I have 3 collections in MongoDB</p>
  
  <ul>
  <li>regions
  
  <ul>
  <li>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</li>
  </ul></li>
  <li>details
  
  <ul>
  <li>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</li>
  </ul></li>
  <li>yield
  
  <ul>
  <li>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</li>
  </ul></li>
  </ul>
  
  <p>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.</p>
  
  <h1>Attempt</h1>
  
  <p>I first tried using straightforward mongodb calls for just a single region</p>
  
  <pre class="lang-js prettyprint-override"><code>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 &lt; docs.length; k++) {
      var regionYield = 0;
  
      for (var j = 0; j &lt; 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 &lt; docs.length; i++) {
            farmYield += +docs[i].Yield;
          }
          console.log('finished inner loop');
  
          regionYield += farmYield;
        });
      }
      console.log('finished middle loop');
    }
    console.log('finished outer loop');
  });
  </code></pre>
  
  <p>After the completion of the outer loop I want to do something with the final <code>regionYield</code> 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. </p>