abhigyan nayak
abhigyan nayak

Reputation: 1444

mongoose.connect(), first argument should be String, received undefined

I am trying to set the test database for the testing purpose, but its not working.

I am trying to connect to MongoDB using mongoose, but finding problem in the connection error shows:

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.
    at new MongooseError (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/error/mongooseError.js:11:11)
    at NativeConnection.Connection.openUri (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/connection.js:424:11)
    at Mongoose.connect (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mongoose/lib/index.js:230:15)
    at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/db/mongoose.js:5:10)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/models/Todo.js:1:82)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/server/tests/server.test.js:4:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at /media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:250:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:247:14)
    at Mocha.run (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/lib/mocha.js:576:10)
    at Object.<anonymous> (/media/abhigyan/ABHI/programming/node js/Practice/On my Own/Todo/node_modules/mocha/bin/_mocha:637:18)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
error Command failed with exit code 1.

I am passing a valid String, but Its not working!

const mongoose = require('mongoose');


mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI, err => {
    if(err) 
        console.log(err);
    } 
);



module.exports = {
    mongoose
};

Here is the Script to run mocha:

export NODE_ENV='test' && mocha server/**/*.test.js

Here is the configuration code:

const config = require('./config.json');

const env = process.env.NODE_ENV.toString() || 'development';

if(env === 'test' || env === 'development') {
    const envConfig = config[env];
    Object.keys(envConfig).forEach(key => {
        process.env[key] = envConfig[key];
    });
};

console.log(env);

Here is the config.json file:

{
    "test": {
        "PORT": 3000,
        "MONGODB_URI": "mongodb://localhost:27017/TodoTest"
    },
    "development": {
        "PORT": 3000,
        "MONGODB_URI": "mongodb://localhost:27017/Todo"
    }
}

Thanks for the help!

Upvotes: 46

Views: 193389

Answers (30)

Muhammad Muneeb Waqas
Muhammad Muneeb Waqas

Reputation: 197

I was deploying my MERN stack web application to Heroku so I came through this error .So I was entering the Mongo_DB_URL in this way in Heroku Config Vars.

"mongodb+srv://aaronhakso:[email protected]/?retryWrites=true&w=majority"

But when I removed these double quotes the error was resolved.I wrote the string in the following way to remove the error

mongodb+srv://aaronhakso:[email protected]/?retryWrites=true&w=majority

Upvotes: 0

Aditi Singh
Aditi Singh

Reputation: 61

I also got stuck with same problem so I fixed it like this..

mongoose.connect('mongodb+srv://username:[email protected]/?retryWrites=true&w=majority',{ useNewUrlParser:true,})

// Using MONGO_URI instead of using process.env.MONGO_URI

Upvotes: 0

Kumawat Lalit
Kumawat Lalit

Reputation: 560

If you are getting the same error, Even after configuring dotenv and setting everything step by step, then you have to restart your MongoDB and server and wait for some time. Look at the images, I have done nothing, just restarted MongoDB, and the server

sometimes it's a mongo server issue enter image description here enter image description here

Upvotes: 0

Mohit Saud
Mohit Saud

Reputation: 115

Also, make sure to call dotenv at the top of the code.
The following code gives you the above error as you mentioned above  
// Connecting to DataBase    
        connectDB();    
        const dotenv = require('dotenv').config();    
The Correct Way  
        const dotenv = require('dotenv').config();    
        // Connecting to DataBase    
        connectDB();    

Upvotes: -1

Md Tobibur Rohman
Md Tobibur Rohman

Reputation: 1

I have faced the same problem. I solved it easily.

  • Step 1: npm install dotenv
  • Step 2: require('dotenv').config()
  • Step 3: Create a .env file
  • Step 4: Push Into this code dot env (.env) file DB_USER = ******** and DB_PASS = ********
  • Step 5:

const dbURL = mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@techbd71.5ewxj.mongodb.net/enter table name here?retryWrites=true&w=majority

mongoose.connect(dbURL, {useNewUrlParser: true, useUnifiedTopology: true})
  .then(()=>console.log('DB Ok'))
  .catch(err => console.log(err))

Upvotes: 0

Surbhi Dighe
Surbhi Dighe

Reputation: 751

Please try the below steps

Step 1 - Install dotenv package

# with npm
npm install dotenv

# with Yarn
yarn add dotenv

Step 2 - Create a new env file e.g config.env

enter image description here

Step 3 - Write the below code in the config.env file

DATABASE = MONGO_URL
PORT = port_number

Step 4 - Write the below code in your main server file (in my case it is index.js)

const dotenv = require("dotenv");  //require dotenv package
dotenv.config({ path: "./config.env" }); //import config.env file

const DB = process.env.DATABASE;  
const Port = process.env.PORT;

mongoose
  .connect(DB, {
    usenewurlparser: true,
    useunifiedtopology: true,
  })
  .then(() => {
    console.log("Successfully connected ");
  })
  .catch((error) => {
    console.log(`can not connect to database, ${error}`);
  });

Upvotes: 2

CodeAbsolute
CodeAbsolute

Reputation: 11

You can check for the ".env" file in your folder has the exact name, else it won't work. If you have named the ".env" file something else then please change it.

Upvotes: 0

Shamshad Hussain
Shamshad Hussain

Reputation: 61

enter image description here

there is a very small mistake Your .env file should exist in your project directory. maybe your .env file is placed in a different folder. check your .env file location

Upvotes: 4

Kritik Sah
Kritik Sah

Reputation: 31

try using this method worked for me.

mongoose.connect(`${process.env.MONGO_URL}`, {useNewUrlParser: true, useUnifiedTopology: true}, ()=>{
    console.log("mongodb is connected")
});

Upvotes: 3

SAISH GADEKAR
SAISH GADEKAR

Reputation: 1

after using require("dotenv").config(); or import dotenv from "dotenv"; dotenv.config(); put your .env file in the same folder as server file

Upvotes: 0

Bahar
Bahar

Reputation: 1

i had a similar issue, Make sure that you have the .env in "/" (next to your package.json file).if do not want to require and load dotenv in your application code or still have an issue run your server through:

node -r dotenv/config your_script.js.


otherwise, if your file containing environment variables is located elsewhere, you have to use path module:

common js: require('dotenv').config({ path: '/custom/path/to/.env' })

ES:dotenv.config({ path: '/custom/path/to/.env' })

Upvotes: 0

ozygz
ozygz

Reputation: 91

i have taken this error message, you have to declare .env file after installing dotenv package. if you declare file before installing package , variable will be undefined

Upvotes: 1

Rishabh Kumar
Rishabh Kumar

Reputation: 81

In the server directory,

  1. npm install dotenv
    
  2. In your server.js: If you use "type":"module" in your package.json file then,

    import dotenv from 'dotenv';
    import mongoose from 'mongoose'; 
    dotenv.config();
    

    or,

    const mongoose = require('mongoose')
    require('dotenv').config()
    
  3. Add a .env file in the server directory,

    PORT=5000
    MONGO_URL= yourURL
    
  4. In the server.js,

    const url = process.env.MONGO_URL
    mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => app.listen(PORT, () => console.log("Server up and running!")
    .catch((error) => console.log(error.message) 
    mongoose.set('useFindAndModify', false)
    

Upvotes: 8

B. Robs
B. Robs

Reputation: 21

my .env file was named .dotenv by mistake. after changing it to .env everything worked 👌

Upvotes: 0

GODSWILL
GODSWILL

Reputation: 21

I came across this same issue and here is my fix: the process.env.MONGODB_URL should be in a string. Check it out

const mongoose = require('mongoose');


mongoose.Promise = global.Promise;
mongoose.connect('process.env.MONGODB_URI', err => {
    if(err) 
        console.log(err);
    } 
);



module.exports = {
    mongoose
};

Upvotes: 0

OriO
OriO

Reputation: 267

i have encountered the same error, this thread didn't help... here's my solution it was simple! im using express, mongo, mongoose, and dotENV

file 1 === db.js

 import mongoose from 'mongoose';

const connectDB =  async ()=>{

    try{
        const conn = await mongoose.connect(process.env.MONGO_URI,{
            //must add in order to not get any error masseges:
            useUnifiedTopology:true,
            useNewUrlParser: true,
            useCreateIndex: true
        })
        console.log(`mongo database is connected!!! ${conn.connection.host} `)
    }catch(error){
        console.error(`Error: ${error} `)
        process.exit(1) //passing 1 - will exit the proccess with error
    }

}

export default connectDB

file 2= server.js

import express from 'express'
import dotenv from 'dotenv'
import connectDB from './config/db.js' // DB connection
import products from './data/products.js'

dotenv.config()
const PORT = process.env.PORT || 5000
const mode = process.env.NODE_ENV

const app = express()

connectDB() //this function connects us to the DB!!!
. . . more code…

> solution: the connectDB() expression must come after the dotenv.config() expression. and that's it ! :)

Upvotes: 6

Caleb Benjamin
Caleb Benjamin

Reputation: 11

const conn = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true
    })

Always put useNewUrlParser:true before putting the useUnifiedTopology:true, and then the rest.

Upvotes: 1

Federick J
Federick J

Reputation: 486

If we don't want to define the path of the .env file like this,

require('dotenv').config({ path: 'ENV_FILENAME' });

we can place .env file in the same place as our main file, which was App.js in my case. So we could directly write

require('dotenv').config()

enter image description here

Upvotes: 0

Yeshi
Yeshi

Reputation: 373

What I was doing wrong was I created js file to store the key:

module.export = {
MONGOURI : "Your Key"
}

and from my app.js I was fetching the key with different keyname like

const {MongoUri} = require('./keys')

after changing MongoUri to MONGOURI , it worked fine.

Upvotes: 0

Mohammed Ramadan
Mohammed Ramadan

Reputation: 723

in case you've forgotten to import/require dotenv, then you can run dotenv before running your app using --require dotenv/config

node --require dotenv/config index.js // regular node command

// nodemon to restart application whenever a file gets changed
nodemon --require dotenv/config index.js

// integrate with babel-node if you're using latest JS features like import/export
nodemon --require dotenv/config index.js --exec babel-node

No need to require dotenv and call config function within codebase. Enjoy!

Upvotes: 0

marquitobb
marquitobb

Reputation: 438

just change the env

const db = process.env.MONGO || 'test'

Upvotes: 0

marquitobb
marquitobb

Reputation: 438

const db = process.env.MONGO || 'test'    
    
mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology:true,
      useCreateIndex: true
    }).then(()=>{
      console.log("conected to mongodb");
    }).catch(error => {
      console.log("mongo error",error);
    })

Upvotes: 0

piouson
piouson

Reputation: 4555

I had same error, for me it was because I was trying to use environment variables in globalSetup which had the file for initiating db connection.. mongoose.connect(global.__MONGO_URI__

enter image description here

Apparently, environment variables are not initialised yet in globalSetup so I had to move the code somewhere else, either to setupFilesAfterEnv or by using Async Test Environment

Upvotes: 0

E MA
E MA

Reputation: 61

I ran into the same problem. 1. I saved my ATLAS_URI ID to a file called .env 2. My .env file was in the wrong directory, that's how the problem cause 3. Solution: I used "ls -a" command to make sure my .env file is in the same location as my server

Upvotes: 6

estrellas oscuras
estrellas oscuras

Reputation: 1

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.

Upvotes: -2

ASHISH R
ASHISH R

Reputation: 4189

To read from .env file you have to install dotenv ( npm i dotenv / yarn add dotenv) and then just add this on top of your file.


const dotenv = require("dotenv");

dotenv.config();

Upvotes: 19

Yilmaz
Yilmaz

Reputation: 49301

Since error message returned UNDEFINED uri parameter, .toString() will NOT work. You can use the String() function: String(your connection parameter).
Also, in if(env === 'test' || env === 'development') try not to use (===), it is a strict equality.

Instead try if(env == 'test' || env == 'development'). This is a loose equality. It doesn't care about the type match and will convert second operand's type to first one's type.

Upvotes: 4

DHIYA A ALJARADI
DHIYA A ALJARADI

Reputation: 11

I had the same problem, but then I realized that I saved the .env file as .env.txt which caused the issue. I deleted the file and created another file without .txt at the end and everything worked find.

I hope this helps.

Dhiya Aljaradi

Upvotes: 1

user9278128
user9278128

Reputation:

This is what solved my problem. Happy Coding!

// Connect to MongoDB
    mongoose.connect('mongodb://yourusername:[email protected]:11025/yourmongodb', {useNewUrlParser: true});
    mongoose.connection.once('open', function(){
      console.log('Conection has been made!');
    }).on('error', function(error){
        console.log('Error is: ', error);
    });

Upvotes: 1

Kenaa
Kenaa

Reputation: 49

Make sure that you have the .env file with the constants that you are using defined.

Upvotes: 0

Related Questions