mongoose连接到mongodb 2.6.1副本集auth失败

时间:2015-04-30 08:07:30

标签: node.js mongodb mongoose

我正在尝试使用mongoose从node.js连接mongodb。 我在连接多台服务器时遇到问题。 我能够连接到单个服务器。 如果我尝试连接多个服务器(因为我想连接到replicasets),它会抛出错误auhtfailed。

var options = {
'db': {
    'native_parser': true
},
'server': {
    'auto_reconnect': true,
    'poolSize': 5,
    'socketOptions' : { 'keepAlive': 1 }
},
'replset': {
    'readPreference': 'nearest',
    'strategy': 'ping',
    'rs_name': 'rs01',
    'socketOptions' : { 'keepAlive': 1 }
}
};

var connect = mongoose.connect('mongodb://adminname:adminpassword@host1:27017,host2:27017,host3:27017/myDatabase', options , function (err) {
"use strict";
if (err) {
    console.log(err);
}else{
    console.log("connected")
}

显示auth失败抛出此错误

  

{[MongoError:auth failed] name:'MongoError',message:'auth failed',ok:0,errmsg:'auth failed',code:18}

1 个答案:

答案 0 :(得分:0)

 mongoConnectionString : "mongodb://dbusername:dbpassword@localhost:27017/db,host2:27017/db,host3:27017/db",

mongoDbOptions : {
    db: {
        native_parser: true
    },
    server: {
        poolSize: 5
    },
    replset: {
        rs_name: 'rplname',
        readPreference: 'ReadPreference.secondaryPreferred'
    },
    pluralization: false,
    host: 'localhost',
    port : '27017'
},
mongoose.connect(mongoConnectionString, mongoDbOptions, function (error) {
    "use strict";
    if (error) {
        console.log(error);
    }
    else {
        console.log("Connection to mongo successful");
    }
});
这对我有用!!感谢; ..