How can you specify the mongodb username and password using a Server instance?


The MongoClient documentation shows how to use a Server instance to create a connection:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server;

// Set up the connection to the local db
var mongoclient = new MongoClient(new Server("localhost", 27017));

How would you specify a username and password for this?

12/26/2012 7:53:16 PM

Accepted Answer

There are two different ways you can do this


Documentation(Note the example in the documentation uses the Db object)

// Your code from the question

// Listen for when the mongoclient is connected, mongoclient) {

  // Then select a database
  var db = mongoclient.db("exampledatabase");

  // Then you can authorize your self
  db.authenticate('username', 'password', function(err, result) {
    // On authorized result=true
    // Not authorized result=false

    // If authorized you can use the database in the db variable


Documentation MongoClient.connect
Documentation The URL
A way I like much more because it is smaller and easier to read.

// Just this code nothing more

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://username:password@localhost:27017/exampledatabase", function(err, db) {
  // Now you can use the database in the db variable
12/26/2012 9:17:01 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow