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
This will create a new directory in your machine.
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
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
In the below image, I’ve used the npm init
command.
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.
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
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.
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.
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}`);
});
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.
Now, let’s run our server with the following command:
node index.js
(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.
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”.
- 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.
The following window will appear and then click on the Compass link.
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/
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.
Add the following code to the .env
file.
MONGODB_URL=<Your MongoDB Connection String>
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
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!");
});
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}`);
});
Restart your server using the node index.js
command. Your terminal output should now look like this.
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
Now run your server using the following command.
nodemon index.js
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)
Great guide! Your steps are clear and easy to follow. I like how you included screenshots to help with setup. Thanks for sharing!
I'm happy you liked it. Thank you so much for your feedback!
Great article Shefali. I enjoyed learning from it
Happy to know that. Thanks a lot, Lucian!