Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using authenticationDatabase option while connecting to mongodb from nodejs

When I connect to mongodb from shell using mongo I need to use the following mongo -u xxxx -p xxxx --authenticationDatabase admin then I get full access... but I cannot find a way to specify the authenticationDatabase while connecting from nodejs this is my code

var MongoCli = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/contactapp";

MongoCli.connect(url,function(err,db){
    if(err)
    {
        console.log('Unable to connect');
    }
    else
    {
        console.log('Connected at ',url);
        db.authenticate('username','password','--authenticationDatabase admin',function(err,res){
            if(err)
            {
                console.log('Error');
            }
            else
            {
                console.log('Auth Success');
                var collection = db.collection('contact');
        collection.find().toArray(function(err,res){
            if(err)
            {
                console.log(err);
            }
            else if(res.length)
            {
                console.log('Found ',res);
            }
            else
            {
                console.log('No data found');
            }
        db.close();
        });    
            }
        }); 
    }
});

I need to use the authenticationDatabase. Thanks in advance.

like image 495
swarnava112 Avatar asked Oct 24 '15 16:10

swarnava112


1 Answers

Try to change this:

db.authenticate('username','password','--authenticationDatabase admin',function(err,res){

Whit this:

db.admin().authenticate('username', 'password', function(err,res){
like image 182
michelem Avatar answered Sep 24 '22 18:09

michelem