由于 mongo 中的 username/password 设置,Nodejs mongoClient.connect 失败

Nodejs mongoClient.connect fails due to username/password setup in mongo

When i try to connect like this it fails when i use database as eventsstore

mongoClient.connect

MongoClient.connect('mongodb://tom:pass@localhost:27017/eventsstore',function(err,db){ if(err){ console.log('NOT CONNECTED') } console.log('CONNECTED') var collection = db.collection('events').insert({mydata:123}, function(err, res){}) })

注意 :数据库 eventsstore 也是由管理员登录创建的

It Passes/connects successfully when i use database as admin

MongoClient.connect('mongodb://tom:pass@localhost:27017/admin',function(err,db){ if(err){ console.log('NOT CONNECTED') } console.log('CONNECTED') var collection = db.collection('events').insert({mydata:123}, function(err, res){}) })

this is how my mongo user tom SUPERUSER permission look in mongo

db.getUser('tom')

[ { "role" : "readWrite", "db" : "admin" }, { "role" : "userAdmin", "db" : "admin" }, { "role" : "dbOwner", "db" : "admin" }, { "role" : "dbAdminAnyDatabase", "db" : "admin" }, { "role" : "userAdminAnyDatabase", "db" : "admin" }, { "role" : "clusterAdmin", "db" : "admin" }, { "role" : "readWriteAnyDatabase", "db" : "admin" } ]

您需要提供身份验证数据库

var opts = {db: {authSource: 'admin'}}

mongo.connect('mongodb://tom:pass@localhost:27017/admin', opts, function(err, db) {

}