title: When to close MongoDB database connection in Nodejs
body: <p>Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example:</p>
  
  <pre><code>db.open(function (err, db) {
    db.collection('foo', function (err, collection) {
      var cursor = collection.find({});
      cursor.each(function (err, doc) {
        if (doc != null) {
          doc.newkey = 'foo'; // Make some changes
          db.save(doc); // Update the document
        } else {
          db.close(); // Closing the connection
        }
      });
    });
  });
  </code></pre>
  
  <p>With asynchronous nature, if the process of updating the document takes longer, then when cursor reaches the end of documents, database connection is closed. Not all updates are saved to the database.</p>
  
  <p>If the <code>db.close()</code> is omitted, all the documents are correctly updated, but the application hangs, never exits.</p>
  
  <p>I saw a post suggesting using a counter to track number of updates, when fall back to zero, then close the db. But am I doing anything wrong here? What is the best way to handle this kind of situation? Does <code>db.close()</code> have to be used to free up resource? Or does a new db connection needs to open?</p>