skip to Main Content

When I run it on my local computer I don’t get any problem, I encounter this error when I deploy it to Heroku. I don’t fully understand the reason.

MongoParseError URI malformed, cannot be parsed

I just get this on Heroku. Also, my file on the server.js side is as follows.

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



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

console.log(DB);

mongoose
  .connect(DB, {
    auth: {
      user: process.env.MONGO_DB_USER,
      password: process.env.MONGO_DB_PASSWORD,
    },
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then(() => console.log("DB connection successful!"));

"mongoose": "^5.13.14", "mongoose-intl": "^3.3.0", "dotenv":
"^16.0.3",

My .env file has MongoDB URLs and passwords. That’s why I don’t share. Works great locally too. but there are problems in deployment.

4

Answers


  1. check your server dotenv value.

    In a cloud environment the .env file may be different.

    can you check local process.env and Heroku’s process.env?

    Login or Signup to reply.
  2. It seems that there is an error in your mongoDB URI
    For now i don’t know what your URI is which is .env file but i can suggest you a few things

    1- Firstly you need to replace the first two lines of your code with this one

    require('dotenv').config();
    

    2- In your .env file you need to create a variable named

    MONGODB_URI=mongodb+srv://[username:password@]host[/[database][?options]]

    whatever your password and username is just fill in that here in URI

    Finally you need to change the connection string and your file should look like this

    require('dotenv').config();
    const app = require("./app");
    
    mongoose
          .connect(process.env.MONGODB_URI)
          .then(() => {
            console.log("Connection Successfull");
          })
          .catch((error) => {
            console.log("Connection Unsuccessfull");
          });
    
    Login or Signup to reply.
  3. If you sure your environment variables are same, it may be related to ip.
    Try adding 0.0.0.0/0 IP address in Atlas Network Access. If you already have this IP, then delete and add it again. After that restart all dynos in Heroku. (inside dropdown menu at top right)

    Login or Signup to reply.
  4. I had the same issue and it was caused by the fact that on heroku the node version was updated to 19.0.0.

    To find out which version of node is being used on heroku, run heroku run ‘node -e "console.log(process.versions)"’

    The error is caused by mongoose version, maybe you are using an old one.

    To solve this, try to update to mongoose 6.7.2 and you should be fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search