DEV Community

Cover image for Full Backend Project Connect MongoDB Atlas in NodeJS Part - 2
SHaon
SHaon

Posted on

Full Backend Project Connect MongoDB Atlas in NodeJS Part - 2

If you complete the first part of this blog series then lets get start with mongoDB. read part-1

  • first of all goto: MONGODB ATLAST login with your email then create a project.

  • then create a cluster and fill-up the form and save the username and password after saving scroll down and allow the IP Address: 0.0.0.0/0 for testing perpose

  • then all done save and click on connect button and click on on the VSCODE option and copy the connection string.

after that open VSCODE select .env file and add the following code with your username and password

PORT=8000
MONGO_URI=mongodb+srv://username:password@cluster0.zvswttn.mongodb.net
Enter fullscreen mode Exit fullscreen mode

save the files.

  • then open the constants.js file and add the following code:
export const DB_NAME = "choose_a_name";
Enter fullscreen mode Exit fullscreen mode
  • then save all the following files

  • then open your terminal and install this following NPM packages mongoose express dotenv

copy the following snippets in your terminal and past

npm i mongoose express dotenv 
Enter fullscreen mode Exit fullscreen mode
  • after successfully installed done open db/index.js file and copy the following code:
import {DB_NAME} from "../constants.js";
import mongoose from "mongoose";

const connectDD = async () => {
    try {
        const connectionDB = await mongoose.connect(`${process.env.MONGO_URI}/${DB_NAME}`);
        console.log(`MONGODB Connected: ${connectionDB.connection.host}`);
    } catch (error) {
        console.log(`MONGODB Connection Error: ${error.message}`);
        process.exit(1);
    }
}

export default connectDD;
Enter fullscreen mode Exit fullscreen mode
  • then save the file and open index.js root file and copy the following code:
import dotenv from "dotenv";
import connectDD from "./db/index.js";

dotenv.config();
connectDD();
Enter fullscreen mode Exit fullscreen mode
  • then save the files and open your terminal and run
npm run dev
Enter fullscreen mode Exit fullscreen mode

Congratulation your database successfully connected with your server

Top comments (0)