Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose .env returning undefined

I am setting up my database connection using a MEVN stack but I am getting the following error;

The `uri` parameter to `openUri()` must be a string, got "undefined"

If I try console log process.env.DATABASE_URL it just returns undefined. What have I done wrong here's my code;

index.js

import dotenv from 'dotenv';
import Express from 'express';
import Mongoose from 'mongoose';

dotenv.config();

const app = Express();

Mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });

app.listen(3000, () => {
    // console.log(process.env.DATABASE_URL);
    console.log('server started on port 3000');
});

.env

DATABASE_URL="mongodb+srv://reece:<password>@mevn-tutorial-cluster-egjs6.mongodb.net/auth?retryWrites=true&w=majority"

I removed my password for obvious reasons

like image 839
Reece Avatar asked Jun 22 '26 03:06

Reece


2 Answers

You have to create a .env file in the root dir of your application. in the .env file you should have key value separate by equal sign. As example:

secret=foo
DATABASE_URL=bar:[email protected]

As the documentation states: https://www.npmjs.com/package/dotenv

like image 63
Danizavtz Avatar answered Jun 24 '26 16:06

Danizavtz


You have not used template literals for mongoose connections.

Try this:

Mongoose.connect(${process.env.DATABASE_URL}, { useNewUrlParser: true });

to get actual .env variable to your Javascript snippet.

like image 35
Ayman Arif Avatar answered Jun 24 '26 15:06

Ayman Arif