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 for more detail.

    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. var options = {
    2. db: { native_parser: true },
    3. server: { poolSize: 5 },
    4. replset: { rs_name: 'myReplicaSetName' },
    5. pass: 'myPassword'
    6. }
    7. 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 we pass a comma delimited list of uris.

    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.

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

      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:

      Next Up

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