Connecting MongoDB to Node JS | Learn MERN Stack

 Step 1 :  SignUp and create a cluster

> Go to MongoDB Website and Create an account - https://www.mongodb.com/

> Create a Project

> Create a Cluster 

  • Shared
  • Cloud Provider - AWS
  • Region - anywhere you like
> Click on Create Clustor















Step 2 : Create an Database

Now the cluster takes 2-3 minutes to create, so by that time let's setup our database


> Got to Database Access

> Add New Database User - setup id and password for the database

> click on create


Step 3: Create Network Access


> Choose "Allow access from anywhere"

> Click on create


Step 4 : 

Now that our cluster is created,

>Go to Database > click on the "Connect" button

> Choose " connect our application"









> Copy the " connection-string "








NOW GO BACK TO YOUR VS CODE EDITOR


Step 5 : 

> go to mern-stack/backend 

>Install Mongoose - npm i mongoose

> Open .env file 

> Create a new variable and paste the "connection string" you just copied"

>.env file : 


PORT = 7000

MONGO_URI = "mongodb+srv://aatu020:<password>@cluster0.t0wil.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"

(Makes sure to replace <password> with your database password)


Step 6 : Creating a Database Connection 

>Create a file name "config" inside backend

> Navigate to notes-saver/backend/config

>Create a java script file with the name "db.js'  (any name is fine)

db.js file - 

------------

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI);
    console.log(`db connected : ${conn.connection.host}`);
  } catch (e) {
    console.log(`Erro : ${e.message}`);
    process.exit();
  }
};

module.exports = connectDB;

>Go to server.js - 

const express = require("express");
const dotenv = require("dotenv");
const notes = require("./Data/notes");
const { connect } = require("mongoose"); //this is added
const connectDB = require("./config/db"); //this is added
const app = express();

dotenv.config();

connectDB(); //this is added

app.get("/", (reqres=> {
  res.send("API is running");
});

app.get("/api/notes", (reqres=> {
  res.send(notes);
});

const PORT = process.env.PORT || 5000;
app.listen(PORTconsole.log(`server started at ${PORT}`));

How do terminal looks -







And connection is successful.


Hurray! You have successfullyestablished the database connection(mongoDB) with backend (nodejs)

0 Comments