×

Html & Html5

The World's best Software Development Study Portal




Node Js MongoDB Connection:



App.js



const express = require ("express")

const mongoose = require ("mongoose")

const dotenv = require('dotenv')

const app = express();

const port = process.env.PORT || 3000

dotenv.config()

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

mongoose.connect(process.env.DATABASE_ACCESS,()=>console.log("Database Connected"))

app.get("/",(req,res)=>{

res.send("Hello to ITC")

});

app.listen(port,()=>{

console.log(`Server is runung on port no ${port}`);

})



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

create file in db folder name as conn.js

const mongoose = require ("mongoose")

//use should have mongo db install in your system

mongoose.connect("mongodb://localhost:27017/nodedatabasename", {

useNewUrlParser:true,

useUnifiedTopology:true

}).then(()=>{

console.log("Database Connect");

}).catch((error)=>{

console.log(error);

})
Now connect this DB file in App.js

require("./db/conn");