Physical Address

Sagipora Sopore Baramulla 193201  Jammu & Kashmir

featured image

How to connect to a MongoDB database with Node.js

connect to a MongoDB database using a Node.js script, retrieve a list of databases, and output the results to the console...

In this tutorial, I will show you how to get started using MongoDB and Node.js from the ground up. We’ll connect to a MongoDB database using a Node.js script, retrieve a list of databases, and output the results to the console in today’s post.

connect to mongodb with node.js
connect to mongodb with node.js

• Steps to Connect to MongoDB Database Using Node.js

We need to make sure you’ve done a few basic steps before we begin.

Installing Node.js

First, make sure you have a version of Node.js that is supported. Node 4.x or higher is required for the current version of MongoDB Node.js Driver. I used Node.js 14.15.4 for these examples. For additional information on which version of Node.js is required for each version of the Node.js driver, see the MongoDB Compatibility documentation.

• Let’s install MongoDB Node.js driver

The MongoDB Node.js Driver makes it simple to work with MongoDB databases from Node.js applications. To connect to your database and run the queries discussed in this Quick Start series, you’ll need the driver.

If you don’t already have the MongoDB Node.js Driver installed, use the following command to do so.

ALSO READ: MongoDB Installation And Setup On Android

npm install mongodb

This driver was installed with version 3.6.4 at the time of writing. The current driver version number may be found by running

npm list mongodb

See the official documentation for further information on the driver and installation.

Load the sample data onto a free MongoDB Atlas cluster.

After that, you’ll require a MongoDB database. Atlas, MongoDB’s fully-managed database-as-a-service, is the simplest way to get started with MongoDB.

To get started, go to Atlas and establish a new cluster using the free tier. A cluster is a collection of computers where copies of your database are stored at a high level. Load the example data into your tier once it’s been built. If you’re not sure how to construct a new cluster and load the sample data.

Get cluster connection details

The last step is to have your cluster ready to connect.

Navigate to your cluster in Atlas and click CONNECT. The Cluster Connection Wizard will then show on the screen.

If you haven’t already done so, the Wizard will prompt you to add your current IP address to the IP Access List and create a MongoDB user. Make a mental note of the new MongoDB user’s username and password because you’ll need them later.

ALSO READ: Nodejs Simplified

The Wizard will next ask you to select a connection method. Connect Your Application is the option to choose. Select Node.js and 3.6 or later when the Wizard asks you to choose your driver version. Copy the connection string that has been provided.

• Connect to database using Node.js

It’s time to code now that everything is set up! Let’s create a Node.js script that connects to your database and displays a list of your cluster’s databases.

MongoClient should be imported.

MongoClient is an export from the MongoDB module that we’ll use to connect to a MongoDB database. We can connect to a cluster, access the database in that cluster, and end the connection to that cluster using a MongoClient instance.

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 }

Inside main(), the first thing we need to do is build a constant for our connection URI. The connection URI is the connection string you copied in the previous section and pasted into Atlas. Remember to adjust username> and password> to the credentials for the user you created in the previous section when you paste the connection string. A dbname> placeholder is included in the connection string. We’ll be using the sample airbnb database in these examples, so replace dbname> with sample airbnb.

Note that the connection string username and password are not the same as your Atlas credentials.

/** * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster. * See for more details */ const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

Creating MongoDB Instance

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

const client = new MongoClient(uri);

Note: You may notice DeprecationWarnings surrounding the URL string parser and the Server Discover and Monitoring engine when you run this code. If you encounter these warnings, you can disable them by giving the MongoClient options. For example, you may run new MongoClient(uri, useNewUrlParser: true, useUnifiedTopology: true) to create a MongoClient. For additional information on these options, see the Node.js MongoDB Driver API documentation.

Now we’re ready to connect to our cluster with MongoClient. A promise will be returned by client.connect(). When we use client.connect(), we’ll use the await keyword to signify that we shouldn’t do anything else until that operation is finished.

await client.connect();

Working with our Database

We’re now ready to work with our database. Let’s create a function that reports the database names in this cluster. To increase the readability of your software, it’s sometimes a good idea to put this logic in well-named functions. As we learn how to construct different types of queries, we’ll create new functions identical to the one we’re creating here throughout this series. Let’s call a method listDatabases for now ().

Also Read: Tesla Website Clone Using React.js | Source Code

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) {

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.


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 for more details
    const uri = "mongodb+srv://<username>:<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) {
    } finally {
        await client.close();


List the databases in our 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();
    databasesList.databases.forEach(db => console.log(` - ${}`));

Save File

You’ve been putting a lot of code in place. Save your modifications and rename the file connection.js to reflect your changes. Visit the nodejs-quickstart GitHub repo to see a copy of the entire file.

Put Your Node.js Script to Work

Now it’s time to put your code to the test! Run the following command in your terminal to execute your script: node connection.js is a node.js library that allows you to

The following is an example of the output:

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

Today, you were able to connect to a MongoDB database from a Node.js script, retrieve a list of databases in your cluster, and view the results in your console. Nice!

If you have any doubt levae a comment below i will try to get back to you ASAP.

• Whats is MongoDB

MongoDB is a cross-platform document-oriented database application that is open source. It is a NoSQL database application that works with JSON-like documents and optional schemas. It was created by MongoDB Inc. and is distributed under the Server Side Public License, which is considered non-free by a number of distributions.

• What is Node.js

Node.js is a cross-platform, open-source back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of a web browser.

• Is Node.js a programming language

Node. js is a web framework, not a programming language. It’s more of a runtime environment for running JavaScript outside of the browser.

• Is MongoDB a programming language

It’s a simple language to pick up and feels like programming, but it’s not programming.

• Is Node.js frontend or backend

Node. js is frequently misunderstood by developers as a backend framework solely for building servers. This isn’t true; Node. js can be used on both the frontend and the backend.

Newsletter Updates

Enter your email address below to subscribe to our newsletter

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Programming & Tech Digest
Programming and Tech innovations delivered straight to your inbox for free.