Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
Oved D Avatar asked Dec 26 '12 19:12

Oved D


People also ask

How do I set MongoDB username and password?

So to create an administrative user first we use the admin database. In this database, we create an admin user using the createUser() method. In this method, we set the user name is “hello_admin”, password is “hello123” and the roles of the admin user are readWrite, config, clusterAdmin.


1 Answers

There are two different ways you can do this

#1

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

// Your code from the question

// Listen for when the mongoclient is connected
mongoclient.open(function(err, 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
  });
});

#2

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
});
like image 128
Mattias Avatar answered Sep 29 '22 12:09

Mattias