Cannot connect to MongoDB in Azure

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@[email protected]:27017/admin';

MongoClient.connect(uri, { useNewUrlParser: true }, (err, db) => {
    assert.strictEqual(null, err);
    // ...
    db.close();
});

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@[email protected]:10355/?ssl=true", function (err, db) {
  db.close();
});

use this

mongoClient.connect("mongodb://myuser:myp%[email protected]: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'); 
});