title: Handling timeouts with Node.js and mongodb
body: <p>I am currently testing how some code stands up against the following scenario:</p>
  
  <ul>
  <li>Node.js application is started and successfully establishes a connection to mongodb</li>
  <li>After it has successfully setup a connection, the mongodb server dies and all subsequent requests fail</li>
  </ul>
  
  <p>To do this I have got the following code which makes use of the official driver (found here: <a href="https://github.com/mongodb/node-mongodb-native">https://github.com/mongodb/node-mongodb-native</a>) :</p>
  
  <pre><code>MongoClient.connect('mongodb://localhost:27017/testdb', function(err, db) {
  app.get('/test', function(req, res) {
      db.collection('users', function (err, collection) {
          console.log(err);
          if (err) {
              // ## POINT 1 ##
              // Handle the error
          }
          else {
              collection.find({ 'username': username }, { timeout: true }).toArray(function(err, items) {
                  console.log(err);
                  if (err) {
                      // ## POINT 2 ##
                      // Handle the error
                  }
                  else {
                      if (items.length &gt; 0) {
                          // Do some stuff with the document that was found
                      }
                      else {
                          // Handle not finding the document
                      }
                  }
              }); 
          }
      });
  });
  </code></pre>
  
  <p>});</p>
  
  <p>As the mongodb server is no longer running when the request is being handled, I'd made the assumption that at either the points which I have labelled ## POINT 1 ## or ## POINT 2 ##, it would return an error indicating a timeout; this however, isn't the case.</p>
  
  <p>I have tried a number of different settings (including one you can see here that explicitly allows the cursor to timeout), however I cannot seem to enable it in any way. In every configuration I've tried Node.js will simply keep waiting for the find() operation to callback and it never does.</p>
  
  <p>If I start the Node.js application <em>before</em> running mongodb, it catches the error in the connect callback fine, but if the connection dies after that it doesn't seem to handle it in any way.</p>
  
  <p>Is there a setting I am missing or is there no way to detect connections being terminated after they've been established?</p>
  
  <p><strong>Edit: just to be clear, the username variable used in the find method is actually declared in my full code, the code I've put in this post is a cut down version to illustrate the structure and error checking.</strong></p>