Navigation

Connection Guide

This guide shows you how to connect to a MongoDB instance or replica set deployment using the Node.js driver.

Connection URI

The connection URI is the set of instructions that the driver uses to connect to a MongoDB deployment. It instructs the driver on how it should connect to MongoDB and how it should behave while connected. The following example shows each part of the connection URI:

/includes/figures/connection_string_parts.png

In this example, for the protocol, we use mongodb+srv which specifies the DNS Seedlist Connection Format. This indicates that the hostname following it corresponds to the DNS SRV record of your MongoDB instance or deployment. If your instance or deployment does not have a DNS SRV record, use mongodb to specify the Standard Connection Format.

note

If your deployment is on MongoDB Atlas, follow the Atlas driver connection guide to retrieve your connection string.

The next part of the connection string contains your username and password if you are using password-based authentication. Replace the value of user with your username and pass with your password. If you are using an authentication mechanism that does not require a username and password, omit this part of the connection URI.

The next part of the connection string specifies the hostname or IP address and port of your MongoDB instance. In the example above, we use sample-hostname as the hostname and 27017 as the port. Replace these values to point to your MongoDB instance.

The last part of the connection string contains connection and authentication options as parameters. In the example above, we set two connection options: poolSize=20 and w=majority. For more information on connection options, skip to the Connection Options section.

The code below shows how you can use the sample connection URI in a client to connect to MongoDB.

const { MongoClient } = require("mongodb");

// Connection URI
const uri =
  "mongodb+srv://sample-hostname:27017/?poolSize=20&w=majority";

// Create a new MongoClient
const client = new MongoClient(uri);

async function run() {
  try {
    // Connect the client to the server
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Connect to a Replica Set

A MongoDB replica set deployment is a group of connected instances that store the same set of data. This configuration of instances provides data redundancy and high data availability.

To connect to a replica set deployment, specify the hostname and port numbers of each instance, separated by a comma, and the replica set name as the value of the replicaSet parameter in the connection string.

mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myRs

note

Although it is possible to connect to a replica set deployment by providing only a single host, you should provide the driver with the full list to ensure that it is able to connect even if one host fails.

Connection Options

This section explains several common MongoDB connection and authentication options. You can pass the connection options as parameters of the connection URI to specify the behavior of the client.

Option NameTypeDefault ValueDescription
validateOptionsbooleanfalseSpecifies whether to error when the method parameters contain an unknown or incorrect option. If false, the driver produces warnings only.
poolSizeinteger5Specifies the maximum size of the instance connection pool.
minSizeinteger0Specifies the minimum size of the instance connection pool.
familynumbernullSpecifies the version of the Internet Protocol (IP). The valid values are: 4, 6, 0, or null. The 0 and null settings attempt to connect with IPv6 and fall back to IPv4 upon failure.
noDelaybooleantrueSpecifies whether to use the TCP socket no-delay option. For more information, see the documentation for Node.js socket.setNoDelay.
keepAlivebooleantrueSpecifies whether to enable keepAlive on the TCP socket. For more information, see the documentation for Node.js socket.setKeepAlive.
keepAliveInitialDelayinteger30000Specifies the number of milliseconds to wait before initiating keepAlive on the TCP socket. For more information, see the documentation for Node.js socket.setKeepAlive.
connectTimeoutMSinteger30000Specifies the number of milliseconds to wait before timeout on a TCP connection.
socketTimeoutMSinteger360000Specifies the number of milliseconds to wait before timeout on a TCP socket.
wstring or integernullSpecifies the write concern. For more information on values, see the server documentation on the w Option.
forceServerObjectIdbooleanfalseSpecifies whether to force the server to assign _id values to documents instead of the driver.
serializeFunctionsbooleanfalseSpecifies whether to serialize functions on any object passed to the server.
ignoreUndefinedbooleanfalseSpecifies whether the BSON serializer should ignore undefined fields.
rawbooleanfalseSpecifies whether to return document results as raw BSON buffers.
promoteLongsbooleantrueSpecifies whether to convert Long values to a number if they fit inside 53 bits of resolution.
promoteBuffersbooleanfalseSpecifies whether to promote Binary BSON values to native Node.js Buffer type data.
promoteValuesbooleantrueSpecifies whether to promote BSON values to Node.js native types when possible. When set to false, it uses wrapper types to present BSON values.
pkFactoryobjectnullSpecifies a primary key factory object that generates custom _id keys.
promiseLibraryobjectnullSpecifies the Promise library class the application uses (e.g. Bluebird). This library must be compatible with ES6.
loggerLevelstringnullSpecifies the logger level used by the driver. Valid choices are: error, warn, info, and debug.
loggerobjectnullSpecifies a custom logger for the client to use.
tlsbooleanfalseSpecifies whether to establish a Transport Layer Security (TLS) connection with the instance. This is automatically set to true when using a DNS seedlist (SRV) in the connection string. You can override this behavor by setting the value to false.

For a complete list of options, see the MongoClient API reference page.