title: Run MongoDB query in loop synchronous in nodejs
body: <p>I'm newbie to NodeJS and MongoDB and I'm stuck in a problem where I have to run a query in loop and the response of query will decide if loop has to be continued.</p>
  
  <p>I have to call an API and pass offset as parameter in it. The API returns 50 records at a time. So, when I get 50 records I increment offset to 51 and call the same API again with offset 51 to get next 50 records. This will go on until API gives less than 50 records. This is the point when I can exit. So, I don't have anything well in advance that can define how long the loop will iterate. It depends on previous API response.
   In each API call I save the data fetched in my db(MongoDB).</p>
  
  <p>Here is my rough code-</p>
  
  <pre><code>var Client = require('node-rest-client').Client;
  var client = new Client();
  var MongoClient = require('mongodb').MongoClient;
  var dburl = "mongodb://localhost:27017/mydb";
  var repeat  =   true;
  var result;
  while(repeat){
      client.get('http://example.com?$offset='+offset, function (data, response) {
           result         =   JSON.parse(data);           
           num_records    =   ret.length;
           MongoClient.connect(dburl, function(err, db) {
               if (err) throw err;
               var collection = db.collection('myCollection');      
               collection.insertMany(result, function(err, res) {
                  if (err) throw err;
                  if(num_records &lt; 50){
                       repeat =   false;
                  }
                  db.close();
               });      
            });
        });
        if(offset==0)
          offset  = 51;
        else
          offset  += 50;
  }
  </code></pre>
  
  <p>This loops infinitely.
  Please help!</p>