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.
Cluster

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.

//db.js

const mongoose = require('mongoose')

const url = `mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority`;

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

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.

Conclusion

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.

Discussion (8)

Collapse
sdutta099 profile image
sdutta099

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 ?

Collapse
dalalrohit profile image
Rohit Dalal Author

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

Collapse
sdutta099 profile image
sdutta099

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

Collapse
chinmay395 profile image
Chinmay-395

Thanks this helped.

Collapse
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.

Collapse
dalalrohit profile image
Rohit Dalal Author

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

Collapse
mayankdev1822 profile image
Mayank-dev1822

Thanks a lot that helped 😄

Collapse
shubhamsaroj23 profile image
shubhamsaroj23

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