Deploying to Heroku: Env variables are undefined

Viewed 414

Disclaimer: This is my first question so any helpful critiques on how to make future ones better is welcome. I'm also relatively new to programming and stack overflow so forgive me if I don't understand some concepts or my question is vague or not understandable.

My Problem: I am trying to deploy my MERN stack app to heroku (im using mongodb atlas) and in my heroku logs its saying that my mongodb uri is undefined instead of a string. My uri is set to an environment variable, and everything works fine on my local machine. When push my code up to heroku though, the uri is suddenly undefined. I've researched the problem and come across various solutions but none of them work. The most common solutionn was to set the env variable on heroku in the config vars section, but that doesn't work either.

Error Message: Error [MongooseError]: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

My Server Code:

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

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
console.log(uri)
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
    console.log('MongoDB database connection made, yay!')
})

const exerciseRouter = require('./routes/exercises')

app.use('/exercises', exerciseRouter);

app.listen(port, () => {
    console.log(`Server is running on port ${port}`)
})

When I run this on my local machine the console.log() function prints out the correct uri and the database connection is successful but the problems still occur when I push this code to heroku.

Let me know if I should provide any more details on the problem, this was all I could think of that would be helpful. Thanks!

0 Answers
Related