I am using .env file to store mongodb uri but i am not able to use it inside my db.js. Here are the screenshots of code. db.js db.js screenshot .env .env screenshot
I am getting this error when i am executing this, instead of this i expect to get no error and connect with my mongodb database. enter image description here
Your uri
variable is undefined
because you are creating it before you call the config()
function so process.env.URI
is not in scope yet. That's why your MongoDB connection error is being thrown.
Simply change the order or execution like so:
const dotenv = require('dotenv');
dotenv.config();
const uri = process.env.URI
.env
APPLES='{"name": "gala"}'
const dotenv = require('dotenv');
dotenv.config();
const apples = JSON.parse(process.env.APPLES);
console.log('apples=', apples.name);
// apples=gala