Vargis.mithun
Vargis.mithun

Reputation: 564

MongoParseError: URI does not have hostname, domain name and tld

I'm getting this error when I try to connect my app(nodejs) to mongodb. I really appreciate your help here.

MongoParseError: URI does not have hostname, domain name and tld
    at parseSrvConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:41:21)
    at parseConnectionString (E:\Projects\NodeAPI\node_modules\mongodb-core\lib\uri_parser.js:509:12)
    at connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:195:3)
    at connectOp (E:\Projects\NodeAPI\node_modules\mongodb\lib\operations\mongo_client_ops.js:284:3)
    at executeOperation (E:\Projects\NodeAPI\node_modules\mongodb\lib\utils.js:416:24)
    at MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:175:10)
    at Function.MongoClient.connect (E:\Projects\NodeAPI\node_modules\mongodb\lib\mongo_client.js:341:22)
    at Object.<anonymous> (E:\Projects\NodeAPI\server.js:12:13)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
  name: 'MongoParseError',
  [Symbol(mongoErrorContextSymbol)]: {} }

My code:

db.js

 module.exports = {
uri : "mongodb+srv://mithun:*******@cluster0-s089x.mongodb.net/test?retryWrites=true"}

==================================================================

node_route.js

 module.exports = function(app, db){
app.post('/notes', (req, res) => {
    const note = {text: req.body.body, title: req.body.title};
    db.collection('notes').insert(note, (err, results) => {
        if(err){
            res.send({'error': 'An error has occured'});
        } else {
            res.send(result.ops[0]);
        }
    });
 });
 };

======================================================================= index.js

 const noteRoutes = require('./note_route');
 module.exports = function(app, db){
 noteRoutes(app, db);
}

========================================================================= server.js

       const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
 app.use(bodyParser.urlencoded({extended: true}));
  MongoClient.connect(db.uri,{ useNewUrlParser: true }, (err, database) => 
  {
     if (err) return console.log(err);
     require('./app/routes')(app, database);
      app.listen(port, () => {
           console.log("We are live on " +port);
  });
 });

===========================================================================

module.exports = {
uri : "mongodb+srv://mithun:m3Thun#[email protected]/test?retryWrites=true&ssl=false"

}

I've tried with ssl= false but the error remains same.

Upvotes: 56

Views: 135973

Answers (23)

Sana Aland
Sana Aland

Reputation: 211

use %23 instead of # in your password and

let mongoURI = "mongodb+srv://username:[email protected]/dbname?retryWrites=true&w=majority" 
mongoose
  .connect(mongoURI, { useNewUrlParser: true })
  .then(() => console.log("MongoDB connected"))
  .catch((err) => console.log(err));

Upvotes: 11

Amit Gupta
Amit Gupta

Reputation: 39

Convert the special characters (: / ? # [ ] @) in your password or username to percentange characters i.e

@ = %40
' = %27
! = %21
others

e.g. p@ssw0rd'9'! becomes p%40ssw0rd%279%27%21

Upvotes: 2

m&#39;hd semps
m&#39;hd semps

Reputation: 684

Convert the special characters (: / ? # [ ] @) in your password or username to percentange characters i.e

  1. @ = %40
  2. ' = %27
  3. ! = %21
  4. others

e.g. p@ssw0rd'9'! becomes p%40ssw0rd%279%27%21

Upvotes: 19

MONGO_URI="mongodb+srv://username:[email protected]/databaseName?retryWrites=true&w=majority"


//db
mongoose
  .connect(process.env.MONGO_URI)
  .then(() => console.log("DB Connected"))
  .catch((err) => console.log("DB ERROR => ", err));

Upvotes: -1

Debendra Dash
Debendra Dash

Reputation: 5626

This error message typically occurs when you're trying to connect to a MongoDB database using an invalid connection string. The password you used contains any special characters which cause parsing error which further restrict the reading of other components like hostname, domain name and tld. Here's what each component represents:

  • mongodb:// is the protocol used for MongoDB connections.

  • username:password is the username and password for the MongoDB database, if authentication is required.

  • host is the hostname or IP address of the server running MongoDB.

  • port is the port number that MongoDB is listening on (usually 27017).

  • database is the name of the database you want to connect to. If your password contain any special character like-

    mongodb+srv://debendra8:Debendra@123@cluster0.f90gm67.mongodb.net/?retryWrites=true&w=majority The Field in Bold letter is Password field and is contain special character @. Check your respective UTF-8 format and replace it from this url enter image description here

So Now my password would be-

mongodb+srv://debendra8:Debendra%[email protected]/?retryWrites=true&w=majority

Now this will resolve your issue.

Upvotes: 1

Shubham K.
Shubham K.

Reputation: 105

Prior to version 3, the library expected properties to be prefixed with env.. The default behaviour going forward is to not use a prefix. If you require a prefix, then you can provide one like this:

prefix=env.

Upvotes: 0

Amarjit Kushwaha
Amarjit Kushwaha

Reputation: 71

I was getting below error while database connection(MongoDB) in my node application:

Error: URI must include hostname, domain name, and tld

I found the documentation for special-characters-in-connection-string-password from official site of MongoDB: Click Here!

As If your password includes special characters, and you are using your password in a connection string URI, encode the special characters.

databaseURI = 'mongodb+srv://<USERNAME>:<PASSWORD>@cluster0.jekotsl.mongodb.net/?retryWrites=true&w=majority'

Root Cause for the reported error: I was entering plain password instead of encoding the special characters.

Solution: I encoded the password from Encode to URL-encoded format , then DB connection was succeeded. enter image description here

Upvotes: 0

shaheb
shaheb

Reputation: 577

If the username or password includes the following characters:

: **/ ? # [ ] @**

those characters must be converted using percent encoding

You can convert using this site-

https://www.w3schools.com/tags/ref_urlencode.ASP

I saw your MONGO_URI password contains # symbole which need to encode to %23

module.exports = {
uri : "mongodb+srv://mithun:m3Thun%[email protected]/test?retryWrites=true&ssl=false"
}

Upvotes: 5

devbiswasnegi
devbiswasnegi

Reputation: 316

remove <> from username and password and password special character is encoded using the website given below

https://www.url-encode-decode.com/

example : @123Password# encoded to %40123Password%23

Upvotes: 0

Sachith Prabhashana
Sachith Prabhashana

Reputation: 31

mongodb+srv://username:[email protected]/database-name

use username and password without <>

Upvotes: 0

The Gentelmen 24
The Gentelmen 24

Reputation: 315

This error occurs because if you use some of the special characters in your passwords like: / ? # [ ] @

  1. Now you have to convert your password to a percentage encoding password so for that put,

@ = %40 (put %40 instead of @)
? = %3F
# = %23
[ = %5B
] = %5D
if some special character doesn't find here use below link.

  1. Just put your password and get the percentage encoded password: https://www.w3schools.com/tags/ref_urlencode.ASP

Upvotes: 5

Abhay Kumar Upadhyay
Abhay Kumar Upadhyay

Reputation: 3017

I Resolved it by these steps in MongoDB Compass:-

  1. Click On "Fill in connection fields individually"

Fill in connection fields individually

  1. fill your Username and password

fill your Username and password

Click on Connect

Upvotes: 0

Manoj
Manoj

Reputation: 2085

Solution-1: If you are using any special character in your password you need to encode the particular character as %+ASCII_code_of_the_character below link explains everything. https://docs.atlas.mongodb.com/troubleshoot-connection/#special-characters-in-connection-string-password

Solution-2: Click on auto-generate password and paste it into the connection string, it will work.

screenshot

Upvotes: 76

WebWorld
WebWorld

Reputation: 31

I think your password may contain & or ? (or may special characters) so u should remove it, cause parsing error

Upvotes: 2

Abdulali
Abdulali

Reputation: 41

try to encode your password

ex)

# before encode
test@#123%^
# after encode
test%40%23123%25%5E

this work for me :)

Upvotes: 4

srujan099
srujan099

Reputation: 21

Even I faced the same issue and I did these steps it got worked for me!

  1. Goto your monogoDB database (website).
  2. Change the user password to automatically generated password.
  3. Paste that auto generated password in the URI string.
  4. Check the URI once and twice and confirm it and run the app in shell.

Upvotes: 2

Adam Reis
Adam Reis

Reputation: 4483

In my case, it turns out I had a space in the connection string, which was hard to see in the small text input field that Heroku provides for config parameters.

Upvotes: 2

Anthony
Anthony

Reputation: 77

I also faced this problem.

In my case, I was using npm dotenv package to get the username the password from a .env file.

When I logged the values from the .env file, I noticed it was not retrieving the password correctly.

It could be an issue with either the username or password.

Upvotes: 4

Aman Singh
Aman Singh

Reputation: 753

This issue comes if your MongoDB User contains any special characters Try removing any special character from the password

Upvotes: 2

Bilbo
Bilbo

Reputation: 355

You might have special characters in your password string.

E.g. If your password was - password!#, !# are special characters, they would have to be rewritten as %23%21. Thus, your connection string password should be password%23%21.

For more information - MongoDB, ASCII

Upvotes: 19

Simon Angatia
Simon Angatia

Reputation: 860

Make sure that the username password is character encoded if you have special characters in it like @!: etc or used MongoDB password generator See: https://docs.mongodb.com/manual/reference/connection-string/#examples

Upvotes: 2

thinclient
thinclient

Reputation: 1441

Ensure special characters in your password are encoded. For example if your password contains '#' you should replace the literal '#' character with '%23' where 23 is the hex code for '#' see: https://docs.atlas.mongodb.com/troubleshoot-connection/#special-characters-in-connection-string-password

Upvotes: 143

patricK
patricK

Reputation: 1105

Use of the +srv connection string modifier automatically sets the ssl option to true for the connection. You can override this behavior by explicitly setting the ssl option to false with ssl=false in the query string.

May it can be a ssl problem? Try with no ssl: ssl=false

Upvotes: 5

Related Questions