DEV Community

Cover image for How to connect to MongoDB Atlas using Node.js
Rohit Dalal
Rohit Dalal

Posted on

How to connect to MongoDB Atlas using Node.js

In this post, I will tell you how you can connect to MongoDB Atlas, a cloud-based DB service, from your local Node.js / Express.js environment.

You can use Atlas for any project which needs to be deployed, whether for development purpose or production environment.

Let's get started!

Step 1: Register/Login and create your plan

Create your account at Atlas and register yourself to their service. It's free of cost. If you already have an account, go ahead. If you logging in for the first time, you will need to choose a plan for your account. There are 3 types to choose from, for testing and learning purpose, "FREE PLAN" will suit your needs perfectly. After doing all basic registration and setup, it's time to create a Cluster.

Step 2: Create your Cluster

After Registration/Login and choosing your plan, let's get our Cluster setup done.

If you have no created clusters, you will see the below page on your dashboard.

Upon clicking "Build a cluster", you will be given with the following options:

Alt Text

Here, on this page, you need to select Cloud Provider, and your Region. Upon selecting those, you can leave all other settings to their default and can go ahead. If you want to change the name of your Cluster, you have to do it in this step only. Name cannot be changed once the cluster is created.

Completing all the above steps is what you need to create a Cluster. Now, MongoDB will configure and create your cluster and this process will take about 5-10 minutes (pretty long tbh). Come back to the same page once all is finished.

We will now look at how to create and configure database collections and integrate it with our express server

Step 3: Add User and whitelist IP address

Till this step, we have successfully created our Cluster. Now, its time to add Database User and IP address of your current machine.

  1. Add database user Go to Database access under SECURITY and click on "Add New Database User". Fill out the username and password, leaving all settings to default and make sure you remember your credentials. We will need it later on to create a connection string (URI) of our DB.

Alt Text

  1. Whitelist your IP address Now, the next step is to Whitelist your IP address so it can recognize your machine for regular access. To whitelist your IP address, go to SECURITY > Network Access and click on "Add IP Address". Upon clicking that, you will be given with the following page. Click on Allow access from anywhere which sets it to global access. Don't worry, its not any danger.

Alt Text

Now, we've all set up done to use it to our Node.js server. It's time for some code.

Step 4: Connect to your database

In this step, we will connect our server to the database. To do this, go to the main page of your cluster and click on "Connect" which will give you a modal like this:

Alt Text

Select "Connect your application". On clicking, you have to select "Node.js" in the next page and save the connection string provided by Atlas somewhere for further use.

Alt Text

Now, its time to create our database connection using mongoose. Install mongoose in your project by npm install mongoose. Copy-paste the following code to db.js.


const mongoose = require('mongoose')

const url = `mongodb+srv://sample_user:<password><dbname>?retryWrites=true&w=majority`;

const connectionParams={
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true 
    .then( () => {
        console.log('Connected to database ')
    .catch( (err) => {
        console.error(`Error connecting to the database. \n${err}`);
Enter fullscreen mode Exit fullscreen mode

Replace "password" with your user password and also the "dbname" with the name you'd like to have for your database. Run the following code by typing node db.js and you will see Connected to the database in your console. You can take this to the next step by configuring your DB model by creating a "Collection" with various fields and connecting it with the express server. I leave it up to you to use according to your need. This was the basic setup needed to get Atlas up and running.


Hooray, this way we have successfully connected to Atlas using Node.js. If you have any doubts, feel free contact me and I will try to resolve it on a personal basis.

Thank you.

Top comments (12)

ararsolatnera profile image
Shibiru A Ararso

const mongoose = require("mongoose");

const url = "mongodb+srv://";

mongoose.connect(url, (err) => {
if (err) throw err;
console.log("Database created!");
I Connect in this way

you explained in details thank you so much

sdutta099 profile image

Is it a good practice to provide mongo admin password in app.js ? as if i push the code to git it might give warning . Btw i am new to node js. if not then what is best way to provide the password of admin in mongo url ?

dalalrohit profile image
Rohit Dalal

you can pass the credentials via environment variables and make sure you don't push that to git. something like is used in production

const url="..<process.env.USERNAME>&<process.env.PASSWORD>";
Enter fullscreen mode Exit fullscreen mode

added this just for demo purpose ;)

sdutta099 profile image

thanks a lot for the reply yes i tried using above step only

chinmay395 profile image

Thanks this helped.

ivanzapatarivera profile image
Ivan J. Zapata-Rivera

Hi, my coding friend!
I believe replacing
const url = ... with
const url = process.env.ATLAS_URI
would be a more secured approach.

dalalrohit profile image
Rohit Dalal

Yes, definitely my coding friend.
I've added , for demo purpose.

mayankdev1822 profile image

Thanks a lot that helped 😄

suyogk38 profile image
Suyog Kubde

const express = require("express");
const app = express();
const { MongoClient } = require("mongodb");
const PORT = 4000;
let db;

let connectionString = mongodb+srv://suyogkubde02:9881815220@cluster0.i2ofrpx.mongod.../?retryWrites=true&w=majority;

// app.use(express.json());

Uploading image:****,
{ useNewUrlParser: true },
(error, client) => {
console.log("error :", error);
console.log("client : ", client);
if (error) {
return console.log("Connection failed for some reason");
console.log("Connection established - All well");
db = client.db("crud");
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);

For now I have just removed the password.
When I do node server.js it doesn't give any error or any output it just keep on loading even the execution don't end.

jhalmu profile image
Juha Halmu

Ah... thanks. This was simple enought for me.

carnato profile image
Vishal Yadav

thanks yar tune meri problem solve kr di!

shubhamsaroj23 profile image

i got this error

MongoParseError: option usecreateindex is not supported

later i came to know usecreateindex is know not supported in mongoos 6 so no need to add it