Error Connecting to Database? Check Your Require Imports

If you are getting an error that the URI parameter to openUri() must be a string in Mongoose, check your main app run file (index.js or similar) to ensure that Mongoose actually has the info required!

I was receiving this error today and it took me a good 15 minutes to solve. I just couldn’t understand why the connection string was returning as undefined instead of the actual MongoDB string that I had added to my .env file in a config folder.

Turns out that – not unlike most scenarios – that I just did something stupid!

In my index.js file I was requiring the dotenv package with its route info after I had called the function that was connecting to the database. With my database connection string stored in the .env file (which for security is then added to the .gitignore file).

In the function that uses Mongoose to connect to the database, the line in my code (inside a try block) that reads const conn = await mongoose.connect (process.env.DB_STRING) was trying to get access to that environment file but with no path information as this was being initiated in the line below 🤦🏻‍♂️

An example of incorrect code that causes an error in connection to a database with mongoose.
These two lines’ order should be reversed in my code to ensure mongoose has access to the connection string.

As a result, the mongoose.connect() function call was taking undefined as its parameter and – for obvious reasons – was then causing a fatal error and causing the app to crash.

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.

Still, it could have been worse I guess… 15 minutes is not such a long time to debug and fix the error – even if it was something so simple!

Onwards and upwards.