I have a MongoDB on Azure and I am trying to connect to it using the npm module mongodb:
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://myuser:mypassword@myhost.documents.azure.com:10355/?ssl=true", function (err, db) {
db.close();
});
Password
My password has the following characteristics:
- Contains letters, lowercase, uppercase
- No white space
- Contains numbers
- Contains special characters like
=
,@
,$
and so on
Error
I get the following when executing the code above:
Error: Password contains an illegal unescaped character
at parseConnectionString (C:\Users\myuser\Documents\myproj\node_modules\mongodb\lib\url_parser.js:280:13)
However the documentation does not tell much about how to solve this issue. I guess it is an encoding problem. How to fix this?
Characters like @ are restricted as they mess up the structure of the URL. The reason for this is because MongoDB interprets it as the @ separator. Instead of this:
use this
To encode the password, use
encodeURIComponent(password)
You can also use this syntax.
On later versions, use
as below
Actually, There is a seperate username for mongoDB and for a database..They have a different passwords too..So, make sure you have
The accepted answer dont work for me on mongodb > 3.0.x
This code work for me :
MongoDB can now use a password with special characters. To do this, add an option to the connection
{ useNewUrlParser: true }
: