Node.js: Connection Pools and MongoDB

Oct 26 2011

Node.js can interact well with MongoDB using the MongoDB native driver. The driver comes with plenty of documentation. However, one feature that isn't explained clearly is the pooling system.

The MongoDB Node library can create a pool of connections to the database that can then be shared throughout your Node application. That means that you can open a series of connections once (at startup) and then use those connections as needed.

Here are the mechanics:


mongodb = require('mongodb');

// Define options. Note poolSize.
var serverOptions = {
  'auto_reconnect': true,
  'poolSize': 5
};

// Now create the server, passing our options.
var serv = new mongodb.Server('localhost', 27017, serverOptions);

// At this point, there is no connection made to the server.

// Create a handle to the Mongo database called 'myDB'.
var dbManager = new mongodb.Db('myDB', serv);

// NOW we initialize ALL 5 connections:
dbManager.open(function (error, db) {
  // Do something with the connection.

  // Make sure to call db.close() when ALL connections need
  // to be shut down.
  db.close();
});

The salient detail of the above code is that the database connections are not opened until Db.open() is called. At that point, all five (our poolSize is 5) will be opened at once. These will be left open until the database is closed.

Internally, the MongoDB library will manage which requests go to which connections.

Note that the variables dbManager and db above both point to the same object. To really make use of pooling, your application will have to do something more sophisticated than the above. After all, there's no sense in opening five connections, executing a single operation, and then closing all five connections. <!--break-->