How To Connect Database Like a pro

How To Connect Database Like a pro

we are use online MongoDB database

Fist of all we create our connection uri from monogdb

  1. Go to mongoDB

  2. signup & create Project

  3. click on connect and copy URI string

click on connect

my wish is go with comapss

now i copy connection String


Now we are go to our code and learn what is good practise to connect server to mongoDB

Basically we have to approach to connect with database

  1. write code in Entry point (index.js)

  2. create a seprate file and write code on that

create an .env file and put our variable

PORT=8000
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.hvtxrru.mongodb.net

warn⚡: MONGODB_URI value not end with '/'

e.g - mongodb+srv://:@cluster0.hvtxrru.mongodb.net

we need a databaseName so if i want to set in .env then i create a simple DB_NAME variable, but it is not any a big confidential data which i need to put in .env file , so we simply make a file which name is constant.js

export default const DB_NAME = "vidtube"

so i give a simple dataname is videtube and export it as a default

  1. write code in Entry point (index.js)

import mongoose in entry point file, we nee to keep one thing in my mind `DataBase Is Always In Another Continent ` so it take time to established connection so we always use async & await and if connection is failed or authorization are wrong then we always use try & catch promises but if i want to use .then & .catch we use it not get any issue but for better approch we need to use try & catch

Also one thing is important, when my server is start then first of all connect with database , so we is IIFE ( Immediately Invoked Function Expression) which is a JavaScript function that runs as soon as it is defined.

 ;(async()=>{
    try{
        mongoose.connect(`${process.env.MONGODB_URI}/${DB_NAME}`)
        app.on("error",()=>{
            console.log("ERRR:", error);
            throw error
        })

        app.listen(process.env.PORT,()=>{
            console.log(`app is listening at port: ${process.env.PORT}`);
        })
    }catch(error){
        console.error("ERROR", error)
        throw error
    }
})()

why i use ; front of IIFE function , because of sometime as a coder we forget end of statement , which is pollute our code so senior developer always apply ; before of IIFE.

why we need app.on , because let if after connection database , if error in own express then we see that what is error

after this we listen our server given PORT

Full Code

import dotenv from "dotenv"
import express from "express"
import mongoose from "mongoose"
import { DB_NAME } from "./constants.js";

dotenv.config({
    path:'./env'
})

const app = express()

 ;(async()=>{
    try{
        mongoose.connect(`${process.env.MONGODB_URI}/${DB_NAME}`)
        app.on("error",()=>{
            console.log("ERRR:", error);
            throw error
        })

        app.listen(process.env.PORT,()=>{
            console.log(`app is listening at port: ${process.env.PORT}`);
        })
    }catch(error){
        console.error("ERROR", error)
        throw error
    }
})()

create a seprate file and write code on that

we write our Database connection code in diffrent file

  1. create a directory name is db and create a file inside this name index.js (file name is your choice)

  2. import mongoose and DB_NAME , if you know we create DB_NAME in a constants.js file.

  3. create an array funtion and apply async & await and use try & catch, in try we store our connection in a variable name connectionInstance, when we console this then we got many intresting thing,

you can see here is many details are available , and confedencial data is available like connection string .

import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";

const connectDB = async()=>{
    try{
       const connectionInstance = await mongoose.connect(`${process.env.MONGODB_URI}/${DB_NAME}`)
       console.log(`\n MongoDB connected !! DB HOST: ${connectionInstance}`)
       console.log(connectionInstance)
    }catch(error){
        console.log("MONGODB Connection error", error);
        process.exit(1)
    }
}

export default connectDB

process.exit() function that automatically stops the NodeJS program when there is some problem with the code

import this database file in your in entry point and call him,

import connectDB from "connectDB"

connectDB()

Run your backend , Hurrah!! we connected successfully 😄😄.

I get the error queryTxt ETIMEOUT jblakdcluster.fti4a.mongodb.net