Connections

We may connect to MongoDB by utilizing the mongoose.connect() method.

  1. mongoose.connect('mongodb://localhost/myapp');

This is the minimum needed to connect the myapp database running locally on the default port (27017). We may also specify several more parameters in the uri depending on your environment:

  1. mongoose.connect('mongodb://username:password@host:port/database?options...');

See the mongodb connection string spec for more detail.

Options

The connect method also accepts an options object which will be passed on to the underlying driver. All options included here take precedence over options passed in the connection string.

  1. mongoose.connect(uri, options);

The following option keys are available:

  1. db - passed to the connection db instance
  2. server - passed to the connection server instance(s)
  3. replset - passed to the connection ReplSet instance
  4. user - username for authentication (if not specified in uri)
  5. pass - password for authentication (if not specified in uri)
  6. auth - options for authentication
  7. mongos - Boolean - if true, enables High Availability support for mongos

Example:

  1. var options = {
  2. db: { native_parser: true },
  3. server: { poolSize: 5 },
  4. replset: { rs_name: 'myReplicaSetName' },
  5. user: 'myUserName',
  6. pass: 'myPassword'
  7. }
  8. mongoose.connect(uri, options);

Note: The server option auto_reconnect is defaulted to true which can be overridden. The db option forceServerObjectId is set to false which cannot be overridden.

See the driver for more information about available options.

A note about keepAlive

For long running applictions it is often prudent to enable keepAlive. Without it, after some period of time you may start to see "connection closed" errors for what seems like no reason. If so, after reading this, you may decide to enable keepAlive:

  1. options.server.socketOptions = options.replset.socketOptions = { keepAlive: 1 };
  2. mongoose.connect(uri, options);

ReplicaSet Connections

The same method is used to connect to a replica set but instead of passing a single uri we pass a comma delimited list of uris.

  1. mongoose.connect('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]' [, options]);

Multi-mongos support

High availability over multiple mongos instances is also supported. Pass a connection string for your mongos instances and set the mongos option to true:

  1. mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);

Multiple connections

So far we’ve seen how to connect to MongoDB using Mongoose’s default connection. At times we may need multiple connections open to Mongo, each with different read/write settings, or maybe just to different databases for example. In these cases we can utilize mongoose.createConnection() which accepts all the arguments already discussed and returns a fresh connection for you.

  1. var conn = mongoose.createConnection('mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]', options);

This connection object can then be used for creating and retrieving models that are scoped only to this specific connection.

Connection pools

Each connection, whether created with mongoose.connect or mongoose.createConnection are all backed by an internal configurable connection pool defaulting to a size of 5. Adjust the pool size using your connection options:

  1. // single server
  2. var uri = 'mongodb://localhost/test';
  3. mongoose.createConnection(uri, { server: { poolSize: 4 }});
  4. // for a replica set
  5. mongoose.createConnection(uri, { replset: { poolSize: 4 }});
  6. // passing the option in the URI works with single or replica sets
  7. var uri = 'mongodb://localhost/test?poolSize=4';
  8. mongoose.createConnection(uri);

Next Up

Now that we’ve covered connections, let’s take a look at how we can break pieces of our functionality out into reusable and shareable plugins.