Introduction
This article will walk you through connecting to a MongoDB database from a Node.js script, retrieving a list of databases, and printing the results to your console.
Table of Contents:
Install Node.js
First, make sure you have a supported version of Node.js installed. The current version of MongoDB Node.js Driver requires Node 4.x or greater. For these examples, we've used Node.js 14.15.4. See the MongoDB Compatability docs for more information on which version of Node.js is required for each version of the Node.js driver.
Install and Connect with the MongoDB Node.js Driver
The MongoDB Node.js Driver allows you to easily interact with MongoDB databases from within Node.js applications. You'll need the driver in order to connect to your database and execute the queries described in this article
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 in your cluster.
Import MongoClient
The MongoDB module exports MongoClient
, and that's what we'll use to connect to a MongoDB database. We can use an instance 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()
where we will connect to 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 thing we need to do inside of main()
is create 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, don't forget to update <username>
and <password>
to be the credentials for the user you created in the previous section. The connection string includes a <dbname>
placeholder. For these examples, we'll be using the sample_airbnb
database, so replace <dbname>
with sample_airbnb
.
Note: The username and password you provide in the connection string are NOT the same as your Atlas credentials.
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/sample_airbnb?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 may see DeprecationWarnings around the URL string parser
and the Server Discover and Monitoring engine. If you see these warnings, you can remove them by passing options to the MongoClient. For example, you could instantiate MongoClient by calling new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true })
. See the Node.js MongoDB Driver API documentation for more information on these options.
Now we're ready to use MongoClient to connect to our cluster. client.connect()
will return a promise. We will use the await keyword when we call client.connect()
to indicate that we should block further execution until that operation has completed.
await client.connect();
We can now interact with our database. Let's build a function that prints the names of the databases in this cluster. It's often useful to contain this logic in well named functions in order to improve the readability of your codebase. Throughout this series, we'll create new functions similar to the function we're creating 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 handle any unexpected errors.
try {
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
}
We want to be sure we close the connection to our cluster, so we'll end our try/catch
with a finally 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 <username>, <password>, and <your-cluster-url> to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/sample_airbnb?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 databases in cluster
In the previous section, we referenced the listDatabases()
function. Let's implement it!
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 a lot of code. Save your changes, and name your file something like connection.js
. To see a copy of the complete file, visit the nodejs-quickstart GitHub repo.
Execute Your Node.js Script
Now you're ready to test your code! Execute your script by running a command like the following in your terminal:
node connection.js
You will see output like the following:
Databases:
- sample_airbnb
- sample_geospatial
- sample_mflix
- sample_supplies
- sample_training
- sample_weatherdata
- admin
- local
Video tutorial
If you'd prefer a more visual walkthrough, check out the video below that covers how to get connected as well as how to perform the CRUD operations.
More resources
Questions? Comments? We'd love to connect with you. Join the conversation on the MongoDB Community Forums.