Can't connect to mongoose

Tell us what’s happening:
I’m not sure I’m using the .env file properly or in the correct way. I’ve required the ‘dotenv’ package, and I checked the spelling on everything so it should work. However, when i copy paste the whole mongo URI to myApp.js directly it works perfectly fine. It also works fine when i commit the .env file to the repo but I dont think i need to do that because it publicly exposes the URI. Could someone help me on how I can use the .env without having to commit it. It’s also defined in the .gitignore that .env files should be ignored, so im really confused why it works when I commit to the repo

Your project link(s)
GitHub repo: GitHub - programmer-boi/boilerplate-mongomongoose: A boilerplate for the freeCodeCamp curriculum.

Your browser information:

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

Challenge: Install and Set Up Mongoose

Link to the challenge:

You can add it to your .gitignore like in the repository you linked to in your original post.

What exactly do you mean?

I mean that when I remove it from the .gitignore list and push the .env file I made into the repo, it connects, and passes the test on freeCodeCamp

Also when I directly put the Mongu URI into the mongoose.connect(); function it works, but obviously I need it from the .env file

Have you tried this article?

Your connection string can look something like this

‘mongodb+srv://${process.env.USERNAME}:${process.env.PASSWORD}’ +‘test?retryWrites=true&w=majority’

Ok I got it to connect to the database, I can tell because it’s connected during the time I deployed to heroku, but for some reason it’s not passing the test on freeCodeCamp. I am not sure what is causing this. Please help

After looking at the assignment it says

Create a .env file and add a MONGO_URI variable to it. Its value should be your MongoDB Atlas database URI. Be sure to surround the URI with single or double quotes, and remember that you can’t use spaces around the = in environment variables. For example, MONGO_URI='VALUE'

so in .env

MONGO_URI=‘mongodb+srv://your username:your’

Then in app.js

mongoose.connect(${MONGO_URI}, { useNewUrlParser: true, useUnifiedTopology: true });

Yes I know that is what I need to do. However when I log to the console the value of the variable I want to use (console.log(process.env.MONGO_URI)) I get undefined but when I log just console.log(process.env) I get a long list of different values.

^^ This is just console.log(process.env)

when I log the variable I want to use i get undefined

Did you try using the Heroku dashboard to add the variables? If so you should have access to them on process.env

I think .env files with Heroku are mainly used in local development.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.