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

你。 提交于 2020-07-05 01:31:27

问题


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 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 help!


回答1:


I think you miss importing env file.

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



回答2:


I was also facing same problem after add code { useNewUrlParser: true } in mongoose.connect() method. Problem resolved.

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



回答3:


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();



回答4:


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.




回答5:


This is what solved my problem. Happy Coding!

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



回答6:


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




回答7:


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




回答8:


I had a similar issue, fixed by adding this code snippet.

mongoose.connect(config.DB,{ useMongoClient:true });



回答9:


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




回答10:


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__

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




回答11:


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);
    })



回答12:


just change the env

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



回答13:


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.



来源:https://stackoverflow.com/questions/51770772/mongoose-connect-first-argument-should-be-string-received-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!