MongoDB Connection

Niraj Chaurasiya
05 July 2024
Visit at:
https://new-blog-app-yt.vercel.app
Table of Contents
The Introduction
The main part when making a full-stack project is its DB. So, we are going to connect our backend application to MongoDB.
Lets directly jump into it.
Learning outcomes
- We are going to create a new project in mongoDB cloud.
- Setting up the root user for cloud project.
- Getting the connection string.
- Using the connection string to connect our app to MongoDB.
Getting MongoDB connection string
First of all, head to https://cloud.mongodb.com , if you don't have a MongoDB account, then you should have an account first. We are not going to discuss the registration process as it is easy and you can create an account with your Github, or Google account.
Now, after signing in, you will be navigated to the dashboard or home page.
Inside the MongoDB logo, there is a box from where we can create a new project, Click on that!
Now, you will get options to enter the project name, go and fill that, and then click Next.
Hence, click on the big green button with text, Create Project.
After clicking on the button, it will take some time to create a project for you depending on the internet connection.
Its time to create a cluster.
After creating a new project, it will redirect you to a page where you can create a cluster, click on, Create.
Now, you have to deploy your cluster, you might see three options, M10, Serverless, and M10. We are going to use the free version as it is free and will be enough for our project. Choose on M10, write the cluster name, and click on create deployement.
Again, the navigated page will provide you two options: the first one is to add a connection IP address which will only allow to do actions with your cluster from the added IP and the second option is to create a database user in which you can create a new user which will gain an access to the created cluster with username and password.
Note: only added IP address and user will be able to access the project's cluster so choose wisely.
Now, close the dialog box, and come to the Databse tab after adding the user and an IP address.
Click on connect button, a dialog box will popup with the long connection string. It will look like this:
mongodb+srv://niraj:<password>@cluster0.dibosvc.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
where niraj = username, and <password> is the password for this user.
Connecting to MongoDB cloud from NodeJS
Now, after successfully getting the connection string, lets move to the mongoDB connection part.
PORT=8000
MONGO_DB_URI=mongodb+srv://niraj:<password>@cluster0.dibosvc.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
# Make sure to replace the <password> with the real one
So, we have successfully added the MONGO_DB_URI in our .env file.
Now, our task is to connect our backend app to MongoDB account. Make two folders as utils, and connection in your root folder. Create constants.js in utils and conn.js in connection folder.
Open constants.js and write the following line!
export const DBName = "new-yt-mern-blog-app";
Open conn.js and write
import mongoose from "mongoose";
import { DBName } from "../utils/constants.js";
const connectDB = async () => {
try {
const connection = await mongoose.connect(
`${process.env.MONGO_DB_URI}/${DBName}`
);
console.log(`Database connected: `, connection.connection.host);
} catch (error) {
console.log(`Mongodb connection failed `, error);
process.exit(1);
}
};
export default connectDB;
If you are wondering without importing and writing configDotenv inside our conn.js file and we are using a environment variable, you should watch the second video of this series on configuration part.
Come to app.js
and write:
import express from "express";
const PORT = process.env.PORT;
const app = express();
import connectDB from "./connection/conn.js";
connectDB();
app.listen(PORT, () => {
console.log(`Backend running on ${PORT}`);
});
Now, run npm start in the terminal. You should see:
┌──(niraj㉿kali)-[~/…/js/reactjs/yt-mern-blog-app-new/backend]
└─$ npm start
> backend@1.0.0 start
> nodemon -r dotenv/config --experimental-json-modules app.js
[nodemon] 3.1.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node -r dotenv/config --experimental-json-modules app.js`
Backend running on 8000
Database connected: ac-q3o0xym-shard-00-01.v53dghk.mongodb.net
This blog is a solid overview about the content of the video, for full explaination about all the codes, refer the video embeded below!
Follow me on X: https://twitter.com/@loveforrobotics
My YouTube channel link where I share amazing videos like this: https://youtube.com/@niraj.chaurasiya
Playlist video on YouTube
https://youtube.com/playlist?list=PLYeR6R4wMO-8ToOG8X7vA7ELDdSX9D2w-&si=w0rpCeXJQYodean7Tags
mern
blog-app