title: Node.js Mongodb-native driver connection sharing
body: <p><em><strong>main.js</em></strong></p>
  
  <pre><code>var http = require('http');
  var UserModel = require('./models/user.js');
  var server = http.createServer(function(req, res){
    UserModel.create({
    }), function(e, o){
      if(e) { console.log(e); } else {
      } console.log(o); }
    });
  }).listen(3000);
  </code></pre>
  
  <p><em><strong>connections.js</em></strong></p>
  
  <pre><code>var mongo = require('mongodb');
  
  module.exports = {
      dbMain: new mongo.Db('main', new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true }, {})),
      dbLog: new mongo.Db('log', new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true }, {}))
  };
  </code></pre>
  
  <p><em><strong>/models/user.js</em></strong></p>
  
  <pre><code>var mongodb = require('mongodb');
  var db = require('./connections.js').dbMain;
  
  module.exports = {
    create: function(newData, callback){
      db.open(function(e, db){
        db.collection('users', function(e, collection){
          collection.insert(newData, callback);
        });
      });
    }
  }
  </code></pre>
  
  <p>When I use the code above, the server crashes with the problem that, the SECOND time a request comes in, we still have the database connection opened, so lets add db.close to our Users.create function.</p>
  
  <pre><code>  create: function(newData, callback){
      db.open(function(e, db){
        db.collection('users', function(e, collection){
          collection.insert(newData, function(e, o){
            db.close(); // Voila.
            callback(e, o);
          });
        });
      });
    }
  </code></pre>
  
  <p>At this stage the server CAN still crash, because of multiple connections open, I don't understand why or how this can happen but it does.</p>
  
  <p>How do I organize my project into models (I don't want to use Mongoose, my validation is done in a different layer not the model, so Mongoose would be an overkill for me)? Also how do I handle connections in the project?</p>