MONGO_URI .env variable is undefined

Hi guys,

I am trying to complete the Exercice tracker project for the Backend development certification. Unfortunatelty I struggle to connect to the mongodb database because I have this error: " MongooseError: The uri parameter to openUri() must be a string, got “undefined”

I double checked my code several times and I don’t understand why I get this. Last time it worked once but now it does not work anymore.

My code so far
Js code:

const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/views/index.html')

mongoose.connect(process.env.MONGO_URI,  { useNewUrlParser: true, useUnifiedTopology: true } )

const listener = app.listen(process.env.PORT || 3000, () => {
    console.log('your app is listening on port ' + listener.address().port)

My .env variable:


My JSON file:

  "name": "code",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "Romifff",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "mongodb": "^5.7.0",
    "mongoose": "^7.4.0"

My browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36 OPR/

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

You are running this locally right?

It looks fine I think, but if the value is undefined it must not be reading it. Maybe try reinstalling the dependencies.

I assume it works if you put the connection string directly inside mongoose.connect()

You might have to post a repo with all the code.

Yep I run locally and it works if I directly past the string

To post a repo ? How would it make it work ?

Did you try reinstalling the dependencies?

If dotenv is installed correctly it should give you access to the .env file values.

It would make it easier for us to debug it if we can see all the code.

There it is: GitHub - Romifff/exercice-tracker: This is an exercise tracker I built while taking the freeCodeCamp backend development & APIs certification
Yep, I tried to reinstall the dependencies

Just to be super clear, the file name is literally .env

It isn’t like a “shorthand” for any env file, it isn’t referring to sample.env (or .local.env or some other variant of a .env file).

I am also unable to access any .env variables. The values are always undefined

Without knowing what your code looks like or where it is running we can’t really help you. Also, you should probably open your own thread instead.

I also got this issue but it was resolved when I put my .env file in the root directory such that put your .env file in the folder in which you are running your main.js or index.js file :slight_smile: