Connections

You can connect to MongoDB with 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). If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed.

You can also specify several more parameters in the uri:

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

See the mongodb connection string spec for more detail.

Operation Buffering

Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.

  1. mongoose.connect('mongodb://localhost/myapp');
  2. var MyModel = mongoose.model('Test', new Schema({ name: String }));
  3. // Works
  4. MyModel.findOne(function(error, result) { /* ... */ });

That’s because mongoose buffers model function calls internally. This buffering is convenient, but also a common source of confusion. Mongoose will not throw any errors by default if you use a model without connecting.

  1. var MyModel = mongoose.model('Test', new Schema({ name: String }));
  2. // Will just hang until mongoose successfully connects
  3. MyModel.findOne(function(error, result) { /* ... */ });
  4. setTimeout(function() {
  5. mongoose.connect('mongodb://localhost/myapp');
  6. }, 60000);

To disable buffering, turn off the bufferCommands option on your schema. If you have bufferCommands on and your connection is hanging, try turning bufferCommands off to see if you haven’t opened a connection properly.

Options

The connect method also accepts an options object which will be passed on to the underlying MongoDB driver.

  1. mongoose.connect(uri, options);

A full list of options can be found on the MongoDB Node.js driver docs for connect(). Mongoose passes options to the driver without modification, modulo three exceptions that are explained below.

  • useMongoClient - This is a mongoose-specific option (not passed to the MongoDB driver) that opts in to mongoose 4.11’s new connection logic. If you are writing a new application, you should set this to true.
  • user/pass - The username and password for authentication. These options are mongoose-specific, they are equivalent to the MongoDB driver’s auth.user and auth.password options.
  • autoIndex - By default, mongoose will automatically build indexes defined in your schema when it connects. This is great for development, but not ideal for large production deployments, because index builds can cause performance degradation. If you set autoIndex to false, mongoose will not automatically build indexes for any model associated with this connection.

Below are some of the options that are important for tuning mongoose.

  • autoReconnect - The underlying MongoDB driver will automatically try to reconnect when it loses connection to MongoDB. Unless you are an extremely advanced user that wants to manage their own connection pool, do not set this option to false.
  • reconnectTries - If you’re connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed event. This option does nothing for replica set connections.
  • reconnectInterval - See reconnectTries
  • promiseLibrary - sets the underlying driver’s promise library
  • poolSize - The maximum number of sockets the MongoDB driver will keep open for this connection. By default, poolSize is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding.
  • bufferMaxEntries - The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set bufferCommands to false on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.

Example:

  1. var options = {
  2. useMongoClient: true,
  3. autoIndex: false, // Don't build indexes
  4. reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  5. reconnectInterval: 500, // Reconnect every 500ms
  6. poolSize: 10, // Maintain up to 10 socket connections
  7. // If not connected, return errors immediately rather than waiting for reconnect
  8. bufferMaxEntries: 0
  9. };
  10. mongoose.connect(uri, options);

Callback

The connect() function also accepts a callback parameter and returns a promise.

  1. mongoose.connect(uri, options, function(error) {
  2. // Check error in initial connection. There is no 2nd param to the callback.
  3. });
  4. // Or using promises
  5. mongoose.connect(uri, options).then(
  6. () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
  7. err => { /** handle initial connection error */ }
  8. );

Connection String Options

You can also specify options in your connection string as parameters in the query string portion of the URI.

  1. mongoose.connect('mongodb://localhost:27017/test?connectTimeoutMS=1000', { useMongoClient: true });
  2. // The above is equivalent to:
  3. mongoose.connect('mongodb://localhost:27017/test', {
  4. useMongoClient: true,
  5. connectTimeoutMS: 1000
  6. });

The disadvantage of putting options in the query string is that query string options are harder to read. The advantage is that you only need a single configuration option, the URI, rather than separate options for socketTimeoutMS, connectTimeoutMS, etc. Best practice is to put options that likely differ between development and production, like replicaSet or ssl, in the connection string, and options that should remain constant, like connectTimeoutMS or poolSize, in the options object.

The MongoDB docs have a full list of supported connection string options

A note about keepAlive

For long running applications, it is often prudent to enable keepAlive with a number of milliseconds. 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: 120 };
  2. mongoose.connect(uri, options);

Replica Set Connections

To connect to a replica set you pass a comma delimited list of hosts to connect to rather than a single host.

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

To connect to a single node replica set, specify the replicaSet option.

  1. mongoose.connect('mongodb://host1:port1/?replicaSet=rsName');

Multi-mongos support

High availability over multiple mongos instances is also supported. Pass a connection string for your mongos instances. If you are not using the useMongoClient option, you must also set the mongos option:

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

With useMongoClient, you do not need to set the mongos option. You also do not need to use mongos or useMongoClient in mongoose 5.x.

  1. mongoose.connect('mongodb://mongosA:27501,mongosB:27501', { useMongoClient: 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 is then used to create and retrieve models. Models are always scoped to a single 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 maximum 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);

The `useMongoClient` Option

Mongoose’s default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you’re upgrading an existing codebase!

  1. // Using `mongoose.connect`...
  2. var promise = mongoose.connect('mongodb://localhost/myapp', {
  3. useMongoClient: true,
  4. /* other options */
  5. });
  6. // Or `createConnection`
  7. var promise = mongoose.createConnection('mongodb://localhost/myapp', {
  8. useMongoClient: true,
  9. /* other options */
  10. });
  11. promise.then(function(db) {
  12. /* Use `db`, for instance `db.model()`
  13. });
  14. // Or, if you already have a connection
  15. connection.openUri('mongodb://localhost/myapp', { /* options */ });

The parameters to openUri() are passed transparently to the underlying MongoDB driver’s MongoClient.connect() function. Please see the driver documentation for this function for options. The same is true for connect() and createConnection() if useMongoClient is true.

You may see the following deprecation warning with useMongoClient:

the server/replset/mongos options are deprecated, all their options are supported at the top level of the options object

In older version of the MongoDB driver you had to specify distinct options for server connections, replica set connections, and mongos connections:

  1. mongoose.connect(myUri, {
  2. server: {
  3. socketOptions: {
  4. socketTimeoutMS: 0,
  5. keepAlive: true
  6. },
  7. reconnectTries: 30
  8. },
  9. replset: {
  10. socketOptions: {
  11. socketTimeoutMS: 0,
  12. keepAlive: true
  13. },
  14. reconnectTries: 30
  15. },
  16. mongos: {
  17. socketOptions: {
  18. socketTimeoutMS: 0,
  19. keepAlive: true
  20. },
  21. reconnectTries: 30
  22. }
  23. });

With useMongoClient you can instead declare these options at the top level, without all that extra nesting. Here’s the list of all supported options.

  1. // Equivalent to the above code
  2. mongoose.connect(myUri, {
  3. socketTimeoutMS: 0,
  4. keepAlive: true,
  5. reconnectTries: 30
  6. });

This deprecation is because the MongoDB driver has deprecated an API that is critical to mongoose’s connection logic to support MongoDB 3.6, see this github issue and this blog post for more details.

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.