Home > Net >  Node.Js MongoParseError URI malformed, cannot be parsed
Node.Js MongoParseError URI malformed, cannot be parsed

Time:11-16

While I run it on my local computer and it doesn't get any problems, I encounter this error when I deploy it to Heroku. I did not 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.

CodePudding user response:

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?

CodePudding user response:

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");
      });
  • Related