Ali
Ali

Reputation: 381

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

I searched a lot about this, but none of them could help me.

When I run my project, I get this error:

/home/ali/Desktop/personalitytest-backend/node_modules/mongoose/lib/connection.js:428 throw new MongooseError('The uri parameter to openUri() must be a ' + ^ 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 index.js file:

const express = require('express'),
  app = express(),
  mongoose = require('mongoose'),
  rateLimit = new require('express-rate-limit')({
    windowMs: 1000 * 60 * 10,
    max: 500,
    handler: (req, res) => {
      res.json({
        data: 'Your request was too much, please try again in 10 minutes later.',
        status: 'error'
      })
    }
  });
const Application = new class {
  constructor() {
    this.setConfig();
    this.setupDB();
    this.setRouters();
    this.setupExpress();
  }
  setConfig() {
    require('dotenv').config();
    app.use(require('helmet')());
    app.use(express.json());
  }
  setupDB() {
    mongoose.Promise = global.Promise;
    mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useCreateIndex: true });
  }
  setRouters() {
    app.use('/', require('./routes'));
  }
  setupExpress() {
    app.listen(process.env.PORT, () => console.log(`Listening on port ${process.env.PORT}.`));
    // app.listen(process.env.PORT, process.env.IP, () => console.log(`Listening on port ${process.env.PORT}.`));
  }
}

My .env file:

PORT=3000
DATABASE_URL=mongodb://localhost:27017/PersonalityTest
JWT_SECRETKEY=asfdawetq312etr%!@$qe

If I simply write database url in mongoose.connect method, there will be no error.

For example, this doesn't have error:

mongoose.connect("mongodb://localhost:27017/PersonalityTest", { useNewUrlParser: true, useCreateIndex: true });

Upvotes: 28

Views: 82641

Answers (24)

justFIDEL
justFIDEL

Reputation: 11

This happened to me recently, my mouse was having an issue, so I mistakenly moved my .env file out of my server.js folder.

Firstly, check if the .env file if its in the server folder.

Secondly, make sure you install something to read the .env file i.e

npm install dotenv --save

Thirdly, require that package in your code i.e

import dotenv from 'dotenv'
dotenv.config()

Sample

Upvotes: 0

Greg
Greg

Reputation: 1

Thank you for the console.log() suggestion. I console.log my MongoURI connection string, and it returned it. And it immediately connected after i did this. No idea why it didn't before this, as that was the only change.

Upvotes: -1

Awara Amini
Awara Amini

Reputation: 592

Please just try to have this order/configuration one after onther.

dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

mongoose
  .connect(process.env.MONGODB_URL)
  .then(() => {
    console.log('connected to db');
  })
  .catch((err) => {
    console.log(err.message);
  });

Upvotes: 0

Koffie Agbobah
Koffie Agbobah

Reputation: 11

Your DATABASE_URL is undefined because your .env file cannot be accessed in the root folder.

Therefore, after importing the dotenv and setting it to config(), make sure your .env file is not saved in another folder. It should always be in the root folder where it can be accessed.

Then in your index.js file:

a code snippet

Upvotes: 1

Sabira Eralathel
Sabira Eralathel

Reputation: 11

  1. Create a .env file and provide MONGOURI in it.

Example:

MONGO_URI=mongodb+srv://<password>@cluster0.wlhevoe.mongodb.net/test

2.In index.js , require like this

const dotenv = require('dotenv')

dotenv.config({ path: './.env' }) // Here you must take care to provide the correct path of the .env file
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })
  .then(() => console.log('DB Connection Successful'));

This worked for me. Thanks

Upvotes: 1

ravi maurya
ravi maurya

Reputation: 11

const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });

const DB = process.env.DATABASE.replace(
  '<PASSWORD>',
  process.env.DATABASE_PASSWORD
);

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true,
  })
  .then((con) => {
    // console.log(con.connections);
    console.log('DB connection successful');
  });
 const port = process.env.PORT || 3000;
 app.listen(port, () => {
       console.log(`app running on port ${port}...`);
  });
  1. Now the problem you facing is related to the path of // config.env to check that you accessing is correct// console.log(process.env); so that it will show you are get access of .env, if not then your path-

     require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
    

Now again console.log(process.env) if you get this in your console read their property is mentioned in config.env file present.

  1. Check the link of your DATABASE and DATABASE_PASSWORD is correct or not or go to mongoDB Atlas change your password for your cluster and again try it

Upvotes: 1

Andrew Solutions
Andrew Solutions

Reputation: 1

Change the .env file to the root of your app at the same level as the package.json

Upvotes: 0

Sharad Gore
Sharad Gore

Reputation: 39

import dotenv from "dotenv";

dotenv.config();

Or:

const dotenv = require("dotenv");

dotenv.config();

No need to add "" for database URL.

Upvotes: 0

owl Night
owl Night

Reputation: 1

I found that when I write

dotenv.config();

before

mongoose.connect(process.env.LOCAL_MONGO);

and my problem solved.

Not written in the constructor.

Upvotes: 0

Sankha Rathnayake
Sankha Rathnayake

Reputation: 843

Make sure that your .env file is also located at the same path where you are executing the nodemon command. Or else you will have to declare the path of .env as in the answer of @oxk4r

Upvotes: 2

Akky...
Akky...

Reputation: 3

mongoose.connect(process.env.MONGO_URI).then(() => {
    console.log('DB Conected...')
})

In my case while connecting to database, I wrote wrong spelling of MONGO_URI , I wrote MANGO_URI there (but in .env file I had given name as MONGO_URI), Please do check & correct it, I know it not proper solution but sometime we do such small mistakes.

Upvotes: 0

ivar
ivar

Reputation: 21

to put : require('dotenv').config(); at the top of the file where all the other "require" are. Then add process.env.DATABASE_URL in a variable: const source = process.env.DATABASE_URL;

and therefore at the top of the file you will have:

require ('dotenv'). config ();
const source = process.env.DATABASE_URL;

lower:

mongoose.connect (source, {useNewUrlParser: true});

Upvotes: 2

Etrix06
Etrix06

Reputation: 1

Check your key and value in your Heroku Config Vars under your app settings. Seems silly, but I had MONGODB_URL instead of _URI and it took me forever to realize my mistake.

Upvotes: 0

MrBrightSide
MrBrightSide

Reputation: 1

I had the same issue and it still persisted even after following all that was stated here. Was losing my mind until I went over the .env and realised I typed DB_NAME:mongodb+srv:/....., changed it to DB_NAME=mongodb+srv:/..... and the variable was no longer undefined, Mongoose was able to read it.

Upvotes: 0

Vivek javiya
Vivek javiya

Reputation: 197

This work for me

const dotenv = require('dotenv')
dotenv.config({path:__dirname+'/.env'});

Upvotes: 5

krishna kurtakoti
krishna kurtakoti

Reputation: 128

Reference to the github repository: https://github.com/realabbas/serverless-lambda-node-express-mongodb

Extending oxk4r's answer, I have the following tree showing the directory structure of the app:

.
├── code-of-conduct.md
├── .env
├── .gitignore
├── _config.yml
├── contributing.md
├── lib
│   ├── app.js
│   ├── db.js
│   └── routes
│       ├── index.js
│       └── notes
│           ├── note.js
│           └── notes.controller.js
├── LICENSE
├── package.json
├── package-lock.json
├── README.md
├── secrets.json
├── server.js
└── serverless.yml

We primarily use the dotenv package to reference the environmental variables in the .env file. The important thing to note here is db.js and the .env files. We need to reference the .env file from the db.js file. We do as below:

db.js

const path = require('path');
const mongoose = require('mongoose')
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
console.log('here...', path.resolve(__dirname, '../.env'), process.env.MONGODB_URL)

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

.env

MONGODB_URL="mongodb://127.0.0.1:27017/game-of-thrones"

As we see the tree, the .env file id one level above the db.js file. So, we reference it by the path package as:

 path.resolve(__dirname, '../.env')

Upvotes: 0

ozygz
ozygz

Reputation: 91

You have to declare .env file after installing dotenv package.

Upvotes: 4

ritik jain
ritik jain

Reputation: 620

I know what the problem is.
Make sure first you write dotenv.config({path: './config.env'}); And then you use your process.env.DATABASE_URL
Don't use process.env.DATABASE_URL before dotenv.config({path:'./config.env'});

Upvotes: 0

kpgabriel
kpgabriel

Reputation: 93

Make sure the .env file is named .env and not config.env or anything else.
I had this problem from following a tutorial online and only recently figured out why I got this error.

file structure

console output

Upvotes: 2

Aman Thakur
Aman Thakur

Reputation: 21

move the .env file from the routes folder or any other folder. And don't place it in any particular folder just let it be in the main folder just like app.js or index.js whichever you have. This might work!

Upvotes: 2

oxk4r
oxk4r

Reputation: 517

Have you checked if your .env variables can be readed from that index.js file?

For example,check out what you get when you log some of them to the console:

console.log(process.env.DATABASE_URL);

If you get 'undefined', then you could try especifiying the absolute path for your .env file like this:

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, './.env') });

I struggled with this problem recently and in my case that solved the issue. Regards.

Upvotes: 13

Faziki
Faziki

Reputation: 821

I had this error and funny enough I had another project that uses a similar setup. Went to that project and started it up with the same .env values and it had no issues.

So I copied the code over the my current project and started the current one but did not want to connect to the mongodb if I have it setup like this mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true },

and will only work if I use it like this mongoose.connect("mongodb://localhost:3000/posts", { useNewUrlParser: true, useCreateIndex: true });

The thing that bothered me is that it works in one project but not in the other so I decided I'm going to delete my node_modules folder and package-lock.json file and reinstall everything.

After that everything worked.

Also Check if you dont have another node_modules folder that is clashing with your current one. if so delete both with your package-lock.json file and reinstall again. make sure you are in the correct directory as well.

Upvotes: 1

user210912
user210912

Reputation: 11

In my case, I had left out the brackets after the word config. So the correct config is below. No more errors now.

require('dotenv').config()

Upvotes: -1

Misantorp
Misantorp

Reputation: 2831

To read the .env-file you'll need to install something that will read that file, for instance the dotenv package

npm install dotenv --save

Then you require that package in your code

require('dotenv').config();

And according to the dotenv documentation you should do it

As early as possible in your application, require and configure dotenv.

Next you might need to add double quotation marks around your DATABASE_URL value

DATABASE_URL="mongodb://localhost:27017/PersonalityTest"

Upvotes: 27

Related Questions