Cannot connect to MongoDB in Azure
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();});
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'); });
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();});