Using authenticationDatabase option when connecting to mongodb from nodejs

when I connect to mongodb from the 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 authenticationDatabase when connecting with 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 in advance authenticationDatabase

+4
source share
1 answer

Try changing this:

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

Take this away:

db.admin().authenticate('username', 'password', function(err,res){
+5
source

Source: https://habr.com/ru/post/1613030/


All Articles