skip to Main Content

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

2

Answers


  1. Put the URL address in the .env file inside double quotes. Like the following code:

    S3_BUCKET="YOURS3BUCKET"
    

    and run the dotenv module as a single line before calling by process:

    require("dotenv").config();
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search