MongooseError: parameter to mongoose.connect() is a string

137 views Asked by At

I am hitting an issue within an app on Heroku, the kind of which I haven't seen at least for a while.

This app is using NextJS (14.0.1) and Express (^4.18.2).

When using this code, I have a problem:

    import mongoose from "mongoose"

    const uri = process.env.MDB_URI_AUDIO!,
                connectMDB = async () => mongoose.connect(uri)

    export default connectMDB

This is the error showing up:

    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.

And I know that the environment variable MDB_URI_AUDIO is correctly set up on the Heroku server.

On the other hand when using code like this, it works fine:

    import mongoose from "mongoose"

    const uri = "mongodb+srv://webuser:[email protected]/VOICE",
                connectMDB = async () => mongoose.connect(uri)

    export default connectMDB

But of course I do not want to use this last code because it is not a good practice to put directly the credentials in the source code.

Though I have seen on the net that this problem has been faced by other people too; I found no solution for me.

Since I have been using the first kind of code in the past, I presume I must be forgetting some important detail, but I don't know what. Can somebody point out what I am (or could be) missing for this problem to occur.

.... Further information:

This is the kind of ouput I get when running the heroku config command.

 % heroku config     
=== myapp Config Vars

MDB_URI_AUDIO: mongodb+srv://webuser:[email protected]/VOICE
 % 

After trying out a few work arounds I noticed the following.

If I use the second version of the code (the wrong one) before running the command npm run build, I avoid problems.

Then I can change the code back to its standard form (first version (i.e. using process.env)) and then run safely:

git add . && git commit -m "myapp update" && git push heroku main

like I always do. And the app works. I am certainly not doing every thing right here, but this is my current state.

0

There are 0 answers