Set Up

Before we begin, we need to ensure you’ve completed a few prerequisite steps.

Install Node.js

First, ensure you’ve got a supported version of Node.js installed. The current version of MongoDB Node.js Driver requires Node 4.x or greater. For those examples, I’ve used Node.js 14.15.4. See the MongoDB Compatability docs for more information on which version of Node.js is required for every version of the Node.js driver.

Install the MongoDB Node.js Driver

The MongoDB Node.js Driver allows you to easily interact with MongoDB databases from inside Node.js applications. You’ll need a driver to order if you want to connect with your database and execute the queries defined in this QuickStart series.

If you don’t have the MongoDB Node.js Driver installed, you can install it with the following command.

npm install mongodb

Create a free MongoDB Atlas cluster and load the sample data

Next, you’ll need a MongoDB database. The easiest way to get started with MongoDB is to use Atlas, MongoDB’s fully-managed database-as-a-service.

Head over to Atlas and create cluster in the free tier. At a high level, a cluster is a group of nodes. And copies of your database will be stored in it. Once your tier is created, load the sample data. If you are not familiar with a way to create a new cluster and load the sample data, check out this video tutorial from MongoDB Developer Advocate Maxime Beugnet.

Get your cluster’s connection info

  1. The final step is to prep your cluster for connection.
  2. In Atlas, navigate to your cluster and click CONNECT. The Cluster Connection Wizard will appear.
  3. The Wizard will prompt you to add your current IP address to the IP Access List and create a MongoDB user if you haven’t already done so. Be sure to note the username and password you use for the new MongoDB user as you’ll need them in a later step.
  4. Next, the Wizard will prompt you to choose a connection method. Select Connect Your Application. When the Wizard prompts you to select your driver version, select Node.js and 3.6 or later. Copy the provided connection string.

Connect to your database from a Node.js application

Now that everything is set up, it’s time to code! Let’s write a Node.js script that connects to your database and lists the databases on your cluster.

Import MongoClient

The MongoDB module exports MongoClient, and that’s what we’ll use to connect with a MongoDB database. We can use an example of MongoClient to connect to a cluster, access the database in that cluster, and close the connection to that cluster.

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

Create our main function

Let’s create an asynchronous function named main() in which we can connect with our MongoDB cluster, call functions that query our database, and disconnect from our cluster.

 async function main() {
   // we'll add code here soon
 }

The first element we want to do inside of main() is creating a constant for our connection URI. The connection URI is the connection string you copied in Atlas in the previous section. When you paste the connection string, recall to update and to be <username> and <password> the credentials for the user you created in the previous section. The connection string consists of a <Database Name> placeholder. For those examples, we’re going to be using the sample_airbnb database, so replace <Database Name> with sample_airbnb.

Note: the username and password you provide in the connection string are NOT similar to your Atlas credentials.

/**
* Connection URI. Update , , and  to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://:@/test?retryWrites=true&w=majority";

Now that we have our URI, we can create an instance of MongoClient.

const client = new MongoClient(uri);

Note: When you run this code, you could see DeprecationWarnings around the URL string parser and the Server Discover and Monitoring engine. If you notice these warnings, you may remove them through passing options to the MongoClient. For example, you can instantiate MongoClient by calling new MongoClient(URI, { useNewUrlParser: true, useUnifiedTopology: true }). See the Node.js MongoDB Driver API documentation for extra information on those options.

Now we are prepared to use MongoClient to connect with our cluster. client.connect() will return a promise. We will use the await keyword while we call client.connect() to indicate that we have to block similar execution until that operation has been completed.

await client.connect();

Now we’re prepared to interact with our database. Let’s build a function that prints the names of the databases on this cluster. It’s often useful to contain this logic is properly named functions in order to improve the readability of your codebase. Throughout this series, we will create new functions much like the function we are developing here as we learn how to write different types of queries. For now, let’s call a function named listDatabases().

await listDatabases(client);

Let’s wrap our calls to functions that interact with the database in a try/catch statement so that we can handle any unexpected errors.

   try {
      await client.connect();

      await listDatabases(client);
   
   } catch (e) {
      console.error(e);
   }

We want to be sure that we close the connection to our cluster, so we’ll end our try/catch with a final statement.

   finally {
      await client.close();
   }

Once we have our main() function written, we need to call it. Let’s send the errors to the console.

   main().catch(console.error);

Putting it all together, our main() function and our call to it will look something like the following.

async function main(){
 /**
 * Connection URI. Update , <password>, and <your-cluster-url> to reflect your cluster.
 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
 */
 const uri = "mongodb+srv://:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
   
  const client = new MongoClient(uri);
 
   try {
     // Connect to the MongoDB cluster
     await client.connect();
   
     // Make the appropriate DB calls
     await  listDatabases(client);
   
  } catch (e) {
     console.error(e);
  } finally {
     await client.close();
   }
 }

main().catch(console.error);

List the databases in our cluster

This function will retrieve a list of databases in our cluster and print the results in the console.

   async function listDatabases(client){
      databasesList = await client.db().admin().listDatabases();
   
      console.log("Databases:");
      databasesList.databases.forEach(db => console.log(` - ${db.name}`));
   };

Save Your File

You’ve been implementing lots of code. Save your changes, and name your document something like connection.js. To see a replica of the entire document, visit the nodejs-quickstart GitHub repo.

Execute Your Node.js Script.

Execute your script by running a command like the following in your terminal: node connection.js

   Databases:
   - sample_airbnb
   - sample_geospatial
   - sample_mflix
   - sample_supplies
   - sample_training
   - sample_weatherdata
   - admin
   - local