在使用Node.js连接到MongoDB时,使用authenticationDatabase选项。

6

当我使用 mongo 命令行连接 MongoDB 时,我需要使用以下命令:mongo -u xxxx -p xxxx --authenticationDatabase admin,然后我就能获得完全访问权限...但是我无法找到在从 Node.js 连接时指定 authenticationDatabase 的方法,这是我的代码:

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();
        });    
            }
        }); 
    }
});

我需要使用authenticationDatabase。提前致谢。

2个回答

6
尝试更改这个:

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

使用以下内容:

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

4

我在使用NodeJS、Mongodb和Mongoose时,也遇到了同样的问题:如何使用authenticationDatabase。对我而言,将凭据和标志与整个路径一起传递是有效的。

mongodb://username:password@127.0.0.1:27017/databaseName?authSource=admin

authSource是指authenticationDatabase的标志。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接