Reputation: 16895
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();
});
My password has the following characteristics:
=
, @
, $
and so onI 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?
Upvotes: 11
Views: 10127
Reputation: 11
MongoDB can now use a password with special characters. To do this, add an option to the connection { useNewUrlParser: true }
:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const uri = 'mongodb://mydbname:pa$s;w@rd@mongodb0.example.com:27017/admin';
MongoClient.connect(uri, { useNewUrlParser: true }, (err, db) => {
assert.strictEqual(null, err);
// ...
db.close();
});
Upvotes: 1
Reputation: 1
Actually, There is a seperate username for mongoDB and for a database..They have a different passwords too..So, make sure you have
Upvotes: 0
Reputation: 618
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:
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://myuser:myp@ssword@myhost.documents.azure.com:10355/?ssl=true", function (err, db) {
db.close();
});
use this
mongoClient.connect("mongodb://myuser:myp%40ssword@myhost.documents.azure.com:10355/?ssl=true", {
uri_decode_auth: true
}, function (err, db) {
db.close();
});
To encode the password, use encodeURIComponent(password)
You can also use this syntax.
mongoClient.connect("mongodb://myhost.documents.azure.com:10355/?ssl=true",
{user: 'username', pass: 'p@ssword'}, function (err, db) {
db.close();
});
On later versions, use
auth: {
user: 'username',
password: 'p@ssword',
}
as below
mongoClient.connect("mongodb://myhost.documents.azure.com:10355/?ssl=true", {
auth: {
user: 'username',
password: 'p@ssword',
}}, function (err, db) {
db.close();
});
Upvotes: 18
Reputation: 790
The accepted answer dont work for me on mongodb > 3.0.x
This code work for me :
const mongoClient = require("mongodb").MongoClient;
let database = null;
new mongoClient('mongodb://myhost.documents.azure.com:10355/?ssl=true', {
auth: {
user: 'username',
password: 'p@ssword',
}
}).connect(
(err, db) => {
if (err) return console.error(err);
console.log('Database connected');
database = db.db('foo');
});
Upvotes: 2