6

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.

2 Answers 2

6

Try to change this:

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

Whit this:

db.admin().authenticate('username', 'password', function(err,res){
Sign up to request clarification or add additional context in comments.

Comments

4

I had the same question on using authenticationDatabase with nodeJS, mongodb and mongoose. Passing the whole path with credentials and a flag worked for me

mongodb://username:[email protected]:27017/databaseName?authSource=admin

authSource is a flag for authenticationDatabase

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.