DEV Community

Cover image for 6 Steps to Set Up MongoDB Atlas for Node.js Applications
Shefali
Shefali

Posted on • Originally published at shefali.dev

6 Steps to Set Up MongoDB Atlas for Node.js Applications

In this post, I’ll share 6 steps to set up MongoDB Atlas for Node.js Applications.

Before starting, I assume you have Node.js, npm, MongoDB, and VS Code installed on your machine.

If you haven’t yet, then you can check the following:

Before we get started, don’t forget to subscribe to my newsletter!
Get the latest tips, tools, and resources to level up your web development skills, delivered straight to your inbox. Subscribe here!

Now let’s dive into the setup!🚀

Step 1: Setting Up the Project

To get started, let’s create a new project folder. Open your terminal and run the following commands one by one.

mkdir mongoDB-project
cd mongoDB-project
Enter fullscreen mode Exit fullscreen mode

This will create a new directory in your machine.

Set Up MongoDB Atlas for Node.js Applications

Now, let’s initialize our project by running the following command in the terminal (make sure you’re in your newly created project folder).

npm init
Enter fullscreen mode Exit fullscreen mode

The above command will walk you through creating a package.json file. Enter the details for the query and hit enter to go to the next query.

Or you can run the below command to create a package.json file with default settings.

npm init -y
Enter fullscreen mode Exit fullscreen mode

In the below image, I’ve used the npm init command.

npm init

After entering all the details a file named package.json will be created in your project folder as you can see in the below image.

MongoDB Package.json file

Step 2: Installing Dependencies

Now let’s install the necessary packages for our project by running the following command in the terminal.

npm install express mongoose dotenv
Enter fullscreen mode Exit fullscreen mode

​The above command will install

  • Express: For building the web server.
  • Mongoose: An ODM (Object Data Modeling) library for MongoDB, which simplifies working with the database in your Node.js app.
  • dotenv: For loading environment variables from a .env file.

After running the above command, this should be the structure of your project folder.

MongoDB Atlas project structure

What is .env file and why do we need it?

A .env file is used to store configuration variables, such as API keys, database credentials, and other sensitive information, separately from the codebase for security purposes.

Note: If you push your code to GitHub, then make sure you don’t push .env file so that no one can access your sensitive information. You can do so by adding .env in your .gitignore file.

Step 3: Set Up a Basic Express app

Create a file named index.js in your root directory.

index.js file for mongoDB atlas

Now, add the following code to the index.js file.

const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
   console.log(`Server is listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

You might be wondering, do I have to remember the above code or from where this code has come?🤔

Let me tell you where you can find this code.

  • Go to expressjs.com
  • Hover over “Getting Started” and click on “Hello world”.
  • You’ll find the code for the basic hello world example.

Express JS

Now, let’s run our server with the following command:

node index.js
Enter fullscreen mode Exit fullscreen mode

(For this command, I’ve used VS Code in-built terminal. You can use your machine’s terminal as well.)

This should be the output in your terminal.

node index.js

In your browser, if you go to localhost:3000 then you’ll see “Hello world!” on the page.

So, our server is running properly.

Step 4: Creating a MongoDB Database

In this step, we will create a Database on MongoDB Atlas.

  • Go to MongoDB Atlas and create an account or sign in if you already have one.
  • If you’re creating a new account then it will ask you to create a username and password, so create those. Then in the second step choose “My Local Environment” and fill in your IP address. After that click on “Finish and Close”.

MongoDB Database

  • Then go to Database (You’ll find it on the left menu) and click on the Create button (on the right side of the screen). Create a Free Shared Cluster.
  • Now on the home page of the cluster, click on the connect button.

MongoDB

The following window will appear and then click on the Compass link.

MongoDB Cluster

Copy the connection string and replace <password> with your password which you’ve created before.

Your connection string should look like this.

mongodb+srv://shefali:********@cluster0.sscvg.mongodb.net/
Enter fullscreen mode Exit fullscreen mode

In your connection string, instead of “shefali” this will display your username, and instead of “********”, your password.

Also, install the MongoDB Compass if you haven’t yet.

What is MongoDB Compass?

MongoDB Compass is a graphical user interface (GUI) that makes it easier to interact with your MongoDB database. It provides an intuitive, visual interface to:

  • View collections and their data.
  • Run queries to search and filter your data.
  • Inspect indexes and other database metrics.
  • Manage the schema of your collections.

While it’s not necessary to use Compass in your Node.js application, it’s highly recommended for developers, especially beginners, as it simplifies the process of managing and interacting with your database.

How to Use MongoDB Compass?

  • Open MongoDB Compass on your computer (you can download it from MongoDB’s official website).
  • Paste the connection string into MongoDB Compass.
  • Click “Connect”, and Compass will establish a connection to your MongoDB Atlas cluster, allowing you to explore and manage your database visually.

Step 5: Creating a .env file

To protect our MongoDB connection string, let’s create a new file named .env in the root directory.

MongoDB Altas Project Structure

Add the following code to the .env file.

MONGODB_URL=<Your MongoDB Connection String>
Enter fullscreen mode Exit fullscreen mode

Replace <Your MongoDB Connection String> with the connection string you obtained from MongoDB Atlas. Now your .env file should look like this.

MONGODB_URL=mongodb+srv://shefali:********@cluster0.sscvg.mongodb.net/mongoDB-project
Enter fullscreen mode Exit fullscreen mode

​In the above string, at last, I’ve added mongoDB-project which is our database name.

Step 6: Connecting to MongoDB using Mongoose

Add the following code to your index.js file to connect the MongoDB.

const mongoose = require('mongoose');
require('dotenv').config(); //for using variables from .env file.
mongoose.connect(process.env.MONGODB_URL).then(() => {
   console.log("MongoDB is connected!");
});
Enter fullscreen mode Exit fullscreen mode

Here process.env.MONGODB_URL will get the connection string from the .env file.

Your final code should look like the following:

const express = require("express");
const app = express();
const port = 3000;
const mongoose = require("mongoose");
require("dotenv").config(); //for using variables from .env file.

mongoose.connect(process.env.MONGODB_URL).then(() => {
  console.log("MongoDB is connected!");
});

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Restart your server using the node index.js command. Your terminal output should now look like this.

connecting mongoDB using mongoose

Note: If you don’t see any changes, then make sure to restart your server.

By using the command node index.js, we have to restart our server each time. To avoid this you can install nodemon using the following command. This restarts the server automatically each time you make the changes to your file.

npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

​Now run your server using the following command.

nodemon index.js
Enter fullscreen mode Exit fullscreen mode

​Congratulations!!🎉

Now that MongoDB Atlas is set up, you’re ready to start building your application. Want to dive deeper into MongoDB with Node.js? Check out my post on building a RESTful API!

That’s all for today.

I hope it was helpful.

Thanks for reading.

Have you used any of these websites? Let me know in the comments!

If you find my articles helpful and would like to support my work, consider buying me a coffee ☕.

For more content like this, click here.

You can also follow me on X(Twitter) for daily web development tips.

Keep Coding!!

Top comments (4)

Collapse
 
tomasdevs profile image
Tomas Stveracek

Great guide! Your steps are clear and easy to follow. I like how you included screenshots to help with setup. Thanks for sharing!

Collapse
 
devshefali profile image
Shefali

I'm happy you liked it. Thank you so much for your feedback!

Collapse
 
devluc profile image
Devluc

Great article Shefali. I enjoyed learning from it

Collapse
 
devshefali profile image
Shefali

Happy to know that. Thanks a lot, Lucian!