Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Connection Guide

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

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:

Each part of the connection string

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: maxPoolSize=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&writeConcern=majority";
// Create a new MongoClient
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
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);

Tip

Reuse Your Client

As each MongoClient represents a pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple requests. To learn more about how connection pools work in the driver, see the FAQ page.

If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:

  1. Download the Community or Enterprise version of MongoDB Server.

  2. Install and configure MongoDB Server.

  3. Start the server.

Important

Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.

After you successfully start your MongoDB server, specify your connection string in your driver connection code.

If your MongoDB Server is running locally, you can use the connection string "mongodb://localhost:<port>" where <port> is the port number you configured your server to listen for incoming connections.

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.

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

When making a connection, the driver takes the following actions by default:

  • Discovers all replica set members when given the address of any one member.

  • Dispatches operations to the appropriate member, such as write against the primary.

Tip

You only need to specify one host to connect to a replica set. However, to ensure connectivity if the specified host is unavailable, provide the full list of hosts.

To force your operations to run on the host specified in your connection URI, you can specify the directConnection connection option. If you specify this option, you must use the standard connection URI format. The driver does not accept the DNS seedlist connection format (SRV) when you specify this option.

When you specify directConnection and connect to a secondary member of the replica set, your write operations fail because it is not the primary member. To perform read operations, you must enable secondary reads. See the read preference options for more information.

←  ConnectionConnection Options →