Docs Home → Develop Applications → MongoDB Drivers → Node.js
Connection Guide
On this page
This guide shows you how to connect to a MongoDB instance or replica set 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:
In this example, we use mongodb
for the protocol, which specifies
the Standard Connection String Format.
If your instance or deployment has a DNS SRV record, you can use the DNS Seed List Connection Format for your connection string. This format offers more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.
Note
To learn how to retrieve your connection string in Atlas, see the Atlas driver connection guide.
The next part of the connection string contains your credentials
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 of
your MongoDB instance, followed by the port number. In the example above, we use
sample.host
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.
Atlas Connection Example
You must create a client to connect to a MongoDB deployment on Atlas. To create
a client, construct an instance of MongoClient
, passing in your
URI and a MongoClientOptions
object.
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.
Use the serverApi
option in your MongoClientOptions
object to
enable the Stable API feature, which forces the server to run operations
with behavior compatible with the specified API version.
The following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:
const { MongoClient, ServerApiVersion } = require("mongodb"); // Replace the placeholder with your Atlas connection string const uri = "<connection string>"; // Create a MongoClient with a MongoClientOptions object to set the Stable API version const client = new MongoClient(uri, { serverApi: { version: ServerApiVersion.v1, strict: true, deprecationErrors: true, } } ); async function run() { try { // Connect the client to the server (optional starting in v4.7) await client.connect(); // Send a ping to confirm a successful connection await client.db("admin").command({ ping: 1 }); console.log("Pinged your deployment. You successfully connected to MongoDB!"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
To learn more about the Stable API feature, see the Stable API page.
Other Ways to Connect to MongoDB
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.
Connect to a MongoDB Server on Your Local Machine
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:
Download the Community or Enterprise version of MongoDB Server.
Install and configure MongoDB Server.
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 following connection string:
mongodb://localhost:<port>
In this connection string, <port>
is the port number on which 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 code example and run it.
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
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
Specify all hosts
To ensure connectivity if one host is unavailable, provide the full list of hosts when connecting to a replica set.
Direct Connection
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 the client isn't
connected to the primary member. To perform read operations, you must
enable secondary reads. See the read preference options
for more information.