title: nodejs mongodb driver drops connection when idle
body: <p>nodejs mongodb driver drops connection when idle and does not reconnect. </p>
  
  <p><strong>Background</strong></p>
  
  <p>The script below connects to mongodb and stores a reference to the database in a global variable "db"</p>
  
  <pre><code>config = require("./config.js");
  express = require("express");
  mongodb = require("mongodb"); 
  
  db = null;
  
  options = {
    auto_reconnect: true,
    db: {
      w: 1
    }
  };
  
  mongodb.MongoClient.connect(config.mongo, options, function(err, database) {
  
    if (err !== null)
      return console.log(err);
  
    db = database;
    console.log("successfully connected to mongodb");
  
    db.on("close", (function() {
      return console.log("Connection to database closed automagically " + arguments);
    }));
  
    db.on("error", function(err) {
      return console.log("Db error " + err);
    });
  
    app.listen(port);
  
    return console.log("listening for connections on " + port);
  
  });
  </code></pre>
  
  <p>Whenever i receive an insert request from client the following function is invoked:</p>
  
  <pre><code>insert = function(collectionName, object) {
    return db.collection(collectionName).insert(object, {w: 1}, (function(err) {
      return console.log("insert complete with err = " + err);
    }));
  };
  </code></pre>
  
  <p><strong>Issue</strong></p>
  
  <p>When the server receives an insert request after a long time it fails silently or sometimes throws an error stating <code>unable to insert object (Error: failed to connect to [host:port])</code></p>
  
  <p><strong>Question</strong></p>
  
  <p>Is there a way to prevent this behaviour? I have tried to use auto_reconnect option and write concern of 1 but none of these have helped. </p>
  
  <p>Thanks!</p>