title: MongoDB connection string in nodejs
body: <p>I am using mongodb with nodejs. My mongodb utility has the following code</p>
  
  <p>In mongodbUtil.js:</p>
  
  <pre><code>var MongoClient = require('mongodb').MongoClient
  
  var state = {
      db: null,
  }
  
  exports.connect = function(url, done) {
      if (state.db) return done()
  
      MongoClient.connect(url, function(err, db) {
          if (err) return done(err)
          state.db = db
          done()
      })
  }
  
  exports.get = function() {
      return state.db
  }
  
  
  /* 1 : when is close called */
  exports.close = function(done) {
      if (state.db) {
          state.db.close(function(err, result) {
              state.db = null
              state.mode = null
              done(err)
          })
      }
  }
  </code></pre>
  
  <p>In app.js I have the following code </p>
  
  <pre><code>var async = require("async");
  var express = require("express");
  var app =  express();
  var db = require("./mongodbUtil");
  
  
  
  db.connect('mongodb://localhost:27017/mydatabase', function(err) {
      if (err) {
          console.log('Unable to connect to Mongo.')
          process.exit(1)
      } else {
          app.listen(3000, function() {
              console.log('Listening on port 3000...')
          })
      }
  })
  
  
  app.get('/',function(req,res){
      res.send("routes :/insert ")
  
  })
  
  
  app.get('/insert',function(req,res){
  
      var collection = db.get().collection('insertcollection');
      collection.drop();
      var obj = {};
  
      for (i=0; i &lt;100000 ; i++){
          obj=({id: i, square:i*i,sum:i+i,subtract:i-1,data:"data part 2014"});
  
          collection.insert(obj.table, function (err, result) {
              if(err) {
                  console.log(err);
  
              } else {
                  console.log(i);
              }
          });
      }
  
  })
  </code></pre>
  
  <p>I have the following query in this code </p>
  
  <ol>
  <li>When should I close the connection in mongodb ? Is this handled by nodejs mongodb driver implicitly or it will just create a connection
  pool in this scenario ?  </li>
  <li>Should I set the connection string with read preference and write preference or should I leave it as the default value ?</li>
  <li>In the insert route only ~60000 records are inserted in the collection. I don't see any error in the mongodb insert callback too.  Is there a particular reason why only partial data is dumped ? (I know that bulk insert is better in performance but I am curious about why no error was reported and only partial data was dumped)</li>
  </ol>