How to Connect MongoDB to Node.js: A Step By Step Guide


INTRODUCTION
Do you use Node.js? Do you need a database to store your data? If the answer is yes, you will most likely be working with MongoDB.
MongoDB is a popular non-relational database system (NoSQL) that pairs perfectly with Node.js, due to its flexibility and scalability.
In this article, I will show you how to connect your Node.js application to MongoDB.
TOOLS/DEPENDENCIES NEEDED
Before we get started, make sure you have the following:
Node.js version 5.x or higher installed
MongoDB Node.js driver
MongoDB Atlas cluster
A basic understanding of Javascript and Node.js
A terminal and a code editor (e.g. VS Code)
PROJECT SET UP
INSTALLING NODE.JS AND NPM
To install Node.js, follow these steps:
Go to the official Node.js website.
Download the latest LTS (Long Term Support) version and install it.
To check if the installation was successful, open your terminal (or command prompt) and run:
node -v npm -v
This will display the versions of Node.js and npm installed on your system.
CREATE PROJECT FOLDER
Once Node.js and npm are installed, the next step is to create a project folder and initialize it. Open your terminal and navigate to the location where you want to create your project folder. Create the folder and move into it using the following commands:
Mkdir mongoDemo
Cd mongoDemo
INITIALIZE THE PROJECT WITH NPM INIT -Y
We will initialize the project with npm init -y.
The -y flag automatically fills in the default values in the package.json
file, which is where the dependencies and settings of the project are stored. It is essential to ensure the package.json file is installed correctly and filled with the right values; otherwise, Node.js will not run properly.
npm init -y
Then create your main file:
touch index.js
INSTALL THE MONGODB NODE.JS DRIVER
The MongoDB Node.js Driver enables seamless interaction with MongoDB databases directly from your Node.js applications. The MongoDB Node.js Driver is essential for connecting to your database and running the queries covered in this Quick Start guide.
To install the MongoDB Node.js Driver, run the following command:
npm install mongodb
At the time of writing, npm install mongodb
installed version 6.17.0 of the driver. Running npm list mongodb will display the currently installed driver version number. For more details on the driver and installation, see the official documentation.
CREATE A MONGODB DATABASE
Next, you’ll need to create a database. The easiest way to begin is by using Atlas, which is a cloud-based service that manages mongoDB for you.
Head over to Atlas, sign up and create a new cluster in the free tier. A cluster is simply a group of servers that work together to host and manage your databases. In MongoDB Atlas (cloud MongoDB), a cluster can hold one or more databases.
Think of a cluster like a building that holds many databases.
CREATE A NEW DATABASE AND COLLECTION
Now that we have everything in place, lt’s time to create a Node.js script that connects to your database.
In this post, we’re focusing only on setting up the connection. We’ll cover database operations like insert, read, update, and Delete in subsequent posts.
IMPORT MONGOCLIENT
The MongoDB module exports MongoClient, and the MongoDB module is 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 the cluster.
const {MongoClient} = require('mongodb');
CREATE A “RUN” FUNCTION
The next step is to create an asynchronous function that will allow us to connect to our MongoDB cluster, call functions that query our database, and disconnect from our cluster. Let’s name the function run()
.
async function run() {
// write your codes here
}
The first step in the run()
function is to define a constant for our connection URI. This URI is the connection string you copied from Atlas in the previous section. When you paste it, make sure to replace <username>
and <password>
with the credentials of the user you created earlier. The connection string also contains a <dbname>
placeholder; so enter the name of your database here.
Note: the username and password you provide in the connection string are NOT the same as your Atlas credentials.
const uri = "<your_mongo_uri_here>"; // Replace with your URI
Now, we can create an instance of MongoClient
const client = new MongoClient(uri);
Note: When executing this code, you might encounter DeprecationWarnings related to the URL string parser and the Server Discover and Monitoring engine. To eliminate these warnings, you can pass options to the MongoClient. For instance, you can create the MongoClient by using new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true })
. Refer to the Node.js MongoDB Driver API documentation for further details on these options.
Now you are ready to connect to our cluster using MongoClient. The client.connect()
method returns a promise, so you will use the await keyword when calling client.connect()
to pause further execution until the operation completes.
await client.connect();
Display a success message to show that the connection was successful.
console.log("Connected to MongoDB successfully!");
Having successfully connected to the database, you have to wrap your call to functions in a try/catch
statement so that you can handle any unexpected errors.
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (err) {
console.error(err);
}
If the connection to the database was not successful, the console.error(err)
displays an error message in the console showing why the connection failed.
After writing your run()
function, you need to call it and then display any errors on the console.
run().catch(console.error);
FULL CODE
Putting all the codes together, your code should look like this:
const { MongoClient } = require("mongodb");
const uri = "<your_mongo_uri_here>"; // Replace with your URI
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
run().catch(console.error);
SAVE FILE
After implementing all the changes in the code, save the changes in the index.js, you created earlier.
RUN YOUR NODE.JS CODE
Now, you’re finally done connecting mongodb to node.js. To run the code, you have to type:
Node index.js
Your output should be:
Connected to MongoDB successfully!
BEST PRACTICES(OPTIONAL BUT RECOMMENDED)
Even if you're just starting out, following these practices helps keep your code secure and easier to manage as your project grows.
Use .env Files for Storing Sensitive Credentials.
Instead of hardcoding your MongoDB connection string directly in your JavaScript code, save it in a
.env
file. Why?Keeps your credentials safe
Makes your codebase easier to share (without exposing secrets).
Works well with GitHub, version control, and deployment platforms.
Learn more about using .env files in this medium article by John Papa.
Move Your DB Logic to a Separate File (db.js)
Keeping your database connection logic in a separate file keeps things modular and easy to manage.
Always Use Error Handling
Wrap your MongoDB operations in
try/catch
blocks or use.catch()
for promises. This ensures your app doesn’t crash unexpectedly and helps you debug issues.
TROUBLESHOOTING TIPS
Double-check your MongoDB URI.
Ensure your Atlas cluster IP whiteli
CONCLUSION
You've successfully connected Node.js to MongoDB! This foundational step enables your applications to interact with your database. In this guide, we:
Installed Node.js and initialized a project.
Installed the MongoDB driver.
Set up a database using MongoDB Atlas.
Connected to the database using a simple script.
Discussed best practices for handling credentials and organizing code.
NEXT STEPS
In future posts, we will explore how to perform CRUD (create, read, update, and delete) operations and build RESTful(Representational State Transfer) APIs(Application Programming Interface) with a database.
Subscribe to my newsletter
Read articles from Mayowa Oladipupo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
