Connections
Connections
You can connect to MongoDB with the mongoose.connect()
method.
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
:
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.
mongoose.connect('mongodb://localhost/myapp'); var MyModel = mongoose.model('Test', new Schema({ name: String })); // Works 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.
var MyModel = mongoose.model('Test', new Schema({ name: String })); // Will just hang until mongoose successfully connects MyModel.findOne(function(error, result) { /* ... */ }); setTimeout(function() { mongoose.connect('mongodb://localhost/myapp'); }, 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 driver. All options included here take precedence over options passed in the connection string.
mongoose.connect(uri, options);
The following option keys are available:
db - passed to the [underlying driver's db instance](http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html) server - passed to the [underlying driver's server instance(s)](http://mongodb.github.io/node-mongodb-native/2.1/api/Server.html) replset - passed to the [underlying driver's ReplSet instance](http://mongodb.github.io/node-mongodb-native/2.1/api/ReplSet.html) user - username for authentication (if not specified in uri) pass - password for authentication (if not specified in uri) auth - options for authentication mongos - passed to the [underlying driver's mongos options](http://mongodb.github.io/node-mongodb-native/2.1/api/Mongos.html) promiseLibrary - sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html)
Example:
var options = { db: { native_parser: true }, server: { poolSize: 5 }, replset: { rs_name: 'myReplicaSetName' }, user: 'myUserName', pass: 'myPassword' } 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.
Note: If auto_reconnect
is on, mongoose will give up trying to reconnect after a certain number of failures. Set the server.reconnectTries
and server.reconnectInterval
options to increase the number of times mongoose will try to reconnect.
// Good way to make sure mongoose never stops trying to reconnect
mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } });
Callback
The connect()
function also accepts a callback parameter and returns a promise.
mongoose.connect(uri, options, function(error) { // Check error in initial connection. There is no 2nd param to the callback. }); // Or using promises mongoose.connect(uri, options).then( () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ }, err => { /** handle initial connection error } );
Connection String Options
Mongoose supports the following options in the connection string.
- ssl
- poolSize
- autoReconnect
- socketTimeoutMS
- connectTimeoutMS
- authSource
- retries
- authMechanism
- reconnectWait
- rs_name
- replicaSet
- nativeParser
- w
- journal
- wtimeoutMS
- readPreference
- readPreferenceTags
- sslValidate
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
:
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 };
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.
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.
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 and set the mongos
option to true:
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.
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 size of 5. Adjust the pool size using your connection options:
// single server var uri = 'mongodb://localhost/test'; mongoose.createConnection(uri, { server: { poolSize: 4 }}); // for a replica set mongoose.createConnection(uri, { replset: { poolSize: 4 }}); // passing the option in the URI works with single or replica sets var uri = 'mongodb://localhost/test?poolSize=4'; mongoose.createConnection(uri);
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!
// Using `mongoose.connect`... var promise = mongoose.connect('mongodb://localhost/myapp', { useMongoClient: true, /* other options */ }); // Or `createConnection` var promise = mongoose.createConnection('mongodb://localhost/myapp', { useMongoClient: true, /* other options */ }); // Or, if you already have a connection connection.openUri('mongodb://localhost/myapp', { /* options */ });
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 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.
© 2010 LearnBoost
Licensed under the MIT License.
http://mongoosejs.com/docs/connections.html