How do I use environment variables in .env file

#.env file

`MONGO_URI="mongodb+srv://dbuser:<password>@cluster0-w5zsv.mongodb.net/test?retryWrites=true&w=majority";`
#Ex-1
//connection failed
 `mongoose.connect( process.env.MONGO_URI,  { useNewUrlParser: true });`
#Ex-2
//connection established
 `mongoose.connect( "mongodb+srv://dbuser:<password>@cluster0-w5zsv.mongodb.net/test?retryWrites=true&w=majority",  { useNewUrlParser: true });`

I am trying to connect to mongodb Atlas, but I am unable to establish connection using .env file (#Ex-1). However, if I substitute the process.env.MONGO_URI with string (#EX-2) then connection is established.
Any help would be appreciated.

SOLVED.
I used the package dotenv, it is basically a zero-dependency module that loads enviorment varibles from .env file.

Usage:
npm install dotenv
require(‘dotenv’).config()
console.log(process.env.MONGO_URI);

Reference:

1 Like