Thanks Mattias for correct answer.
I would like to add that sometimes you have credentials from one database while want to connect to another.
In that case, you can still use URL way to connect, just adding ?authSource=
parameter to URL.
For example, let say you have admin credentials from database admin
, and want to connect to database mydb
. You can do it the following way:
const MongoClient = require('mongodb').MongoClient;
(async() => {
const db = await MongoClient.connect('mongodb://adminUsername:adminPassword@localhost:27017/mydb?authSource=admin');
// now you can use db:
const collection = await db.collection('mycollection');
const records = await collection.find().toArray();
...
})();
Also, if your password contains special characters, you still can use URL way like this:
const dbUrl = `mongodb://adminUsername:${encodeURIComponent(adminPassword)}@localhost:27017/mydb?authSource=admin`;
const db = await MongoClient.connect(dbUrl);
Note: In earlier versions, { uri_decode_auth: true }
option was required (as second parameter to connect
method) when using encodeURIComponent
for username or password, however now this option is obsolete, it works fine without it.