Unhandled promise rejection: Error: URL malformed, cannot be parsed

My issue was a more simple URI issue. Since there was an @ character in the mongod address.

I had to use this:

return mongoose.connect(encodeURI(process.env.DB_CONNECT)); //added ');'

If you used the following URI in your environment file for example MongoDB://<dbuser>:<dbpassword>@ds055915.mlab.com:55915/fullstack-vue-graphql Make sure your password inMONGOD_URI does not have a special character like @. I had used @ as part of my password character and was getting the error. After I removed special characters from my DB Password, all worked as expected.


In my case the below worked fine.

Inside db.js

const mongoose = require('mongoose');
const MONGODB_URI = "mongodb://host-name:27017/db-name?authSource=admin";
const MONGODB_USER = "mongouser";
const MONGODB_PASS = "myasri*$atIP38:nG*#o";

const authData =  {
    "user": MONGODB_USER,
    "pass": MONGODB_PASS,
    "useNewUrlParser": true,
    "useCreateIndex": true
}; 
mongoose.connect(
    MONGODB_URI, 
    authData,
    (err) => {
        if (!err) { console.log('MongoDB connection succeeded.'); }
        else { console.log('Error in MongoDB connection : ' + JSON.stringify(err, undefined, 2)); }
    }
);

Note:

My Node version is 10.x

MongoDb server version is 3.6.3

mongoose version is ^5.1.2


Mongoose 5.x supports following syntax for authorization and also make sure you have not used any special character in url like @,-,+,>

mongoose.connect(MONGO_URL, {
  auth: {
    user: MONGO_DB_USER,
    password: MONGO_DB_PASSWORD
  }
})

Or if you want to remove deprication warning Avoid “current URL string parser is deprecated"

Add option useNewUrlParser

mongoose.connect(MONGO_URL, {
  auth: {
    user: MONGO_DB_USER,
    password: MONGO_DB_PASSWORD
  },
  { useNewUrlParser: true }
})