1

我有一个 MongoDB Atlas 实例,并且能够连接到它,但我无法创建帐户并从 node.js 访问数据库。在使用下面的 mongo 命令 & > 'use mytestcollection' 后,我可以从 Mongo Shell 访问数据库。尝试直接从 shell 访问我的 testcollection 返回“错误身份验证失败”。

这是外壳连接字符串..

mongo mongodb://<atlasDB>-1-shard-00-00-<string>.mongodb.net:27017,<atlasDB>-1-shard-00-01-<string>.mongodb.net:27017,<atlasDB>-1-shard-00-02-<string>.mongodb.net:27017/admin?replicaSet=<atlasDB>-1-shard-0 --ssl --username <account>  --password <password>

这是 Node.js 代码

var uri = "mongodb://<atlasDB>-1-shard-00-00-<string>.mongodb.net:27017,"+
                    "<atlasDB>-1-shard-00-01-<string>.mongodb.net:27017,"+
                    "<atlasDB>-1-shard-00-02-<string>.mongodb.net:27017/mytestcollection?"+
                    "replicaSet=-1-shard-0"+
                    "&ssl=true"+
                    "&authSource=<admin>"+
                    "&username=<account>"+
                    "&password=<password>"

节点代码是......

MongoDB.connect(uri,function(e,db) { 
        if ( e ) { console.error('Mongo Failed'); return console.log(e); } 
        console.log('MongoSuccess');
        db.collection('mytestcollection').find().toArray(function(e,d) {
             if ( e ) { console.log('error'); console.log(e);  }
             if ( d ) { console.log('test.length',d.length); }
        });
 });

错误是...

MongoSuccess
error
{ MongoError: not authorized on test to execute command { find: "mytestcollection", filter: {} }
at Function.MongoError.create (/home/ec2-user/frame/node_modules/mongodb-core/lib/error.js:31:11)
at queryCallback (/home/ec2-user/frame/node_modules/mongodb-core/lib/cursor.js:206:36)
at /home/ec2-user/frame/node_modules/mongodb-core/lib/connection/pool.js:430:18
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoError',
message: 'not authorized on test to execute command { find: "mytestcollection", filter: {} }',
ok: 0,
errmsg: 'not authorized on test to execute command { find: "mytestcollection", filter: {} }',
code: 13 }

欢迎任何建议。

4

1 回答 1

2

您需要洗牌MongoDB URIusername并正确进行password身份验证。您还需要在参数之前指定数据库名称replicaSet,而不是集合名称。有关如何格式化 MongoDB URI 的更多信息,请参阅标准连接字符串格式。

根据您的示例:

var uri = "mongodb://[username:password@]<atlasDB>-1-shard-00-00-<string>.mongodb.net:27017,"+
                "<atlasDB>-1-shard-00-01-<string>.mongodb.net:27017,"+
                "<atlasDB>-1-shard-00-02-<string>.mongodb.net:27017/databaseName?"+
                "replicaSet=-1-shard-0"+
                "&ssl=true"+
                "&authSource=<admin>";

MongoClient.connect(uri, function(err, db) {
        if ( e ) { console.error('Connection Failed'); return console.log(e); } 
        console.log("Connected");

        db.collection('collectionName').find().toArray(function(e,d) {
             if ( e ) { console.log('error'); console.log(e);  }
             console.log(d);
        });

        db.close();    
});

上面的代码片段是使用MongoDB Node.js 驱动程序 v2.2测试的

也可以看看:

于 2016-08-30T00:27:44.307 回答