Search code examples
javascriptnode.jsmongoosedotenv

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


Solution

  • 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