to setup the environment variable through dotenv module
firstly install dotenv module
npm install dotenv
Now create the .env file in the root folder of your project
in the .env file put the below code
Write the credentials
DB_HOST=localhost
DB_USER=root
DB_PASS=12sdf
DB_NAME=myportal
Now include the env module in your main file like server.js
const env_result =require('dotenv').config();
// Now, get the envorment credentials through
process.env.enviormentVariableName like "process.env.DB_HOST"
include the environment credentials into server.js
var MongoClient = require('mongodb').MongoClient;
var url = `mongodb://${encodeURIComponent(process.env.DB_USER)}:${encodeURIComponent(process.env.DB_PASS)}@localhost:27017/process.env.DB_NAME`;
// Connect to the db
MongoClient.connect(url, function (err, db) {
if(err) throw err;
console.log("Database connected");
});