Mongoose connection to replica set

戏子无情 提交于 2019-11-30 07:13:20

We use this:

if(config.db.indexOf('replicaSet') > - 1) {
  dbOptions = {
    db: {native_parser: true},
    replset: {
      auto_reconnect:false,
      poolSize: 10,
      socketOptions: {
        keepAlive: 1000,
        connectTimeoutMS: 30000
      }
    },
    server: {
      poolSize: 5,
      socketOptions: {
        keepAlive: 1000,
        connectTimeoutMS: 30000
      }
    }
  };
}

var db = mongoose.connect(config.db, dbOptions);

where

config.db =  'mongodb://USER:PW@host1:port1,host2:port2/DBNAME?replicaSet=RSNAME'

Auto_reconnect is off as per https://team.goodeggs.com/reconnecting-to-mongodb-when-mongoose-connect-fails-at-startup-83ca8496ca02

I had trouble with this too. What I learned from the experience is:

The "server" block is only invoked when the connection URI contain a single non clustered connection (aka a single connection string).

The "replset" block is only invoked when the connection URL contains a list of comma separated connection strings (aka replication set).

var options = {

    db: {
        native_parser: true
    },

    // This block gets run for a non replica set connection string (eg. localhost with a single DB)
    server: {
        poolSize: 5,
        reconnectTries: Number.MAX_VALUE,
        ssl: false,
        sslValidate: false,
        socketOptions: {
            keepAlive: 1000,
            connectTimeoutMS: 30000
        }
    },

    // This block gets run when the connection string indicates a replica set (comma seperated connections)
    replset: {
        auto_reconnect: false,
        poolSize: 10,
        connectWithNoPrimary: true,
        ssl: true,
        sslValidate: false,
        socketOptions: {
            keepAlive: 1000,
            connectTimeoutMS: 30000
        }
    }
};

This block worked on both localhost and the production env. Hope it helps.

Your connection string is probably invalid. You should provide URI for every replica set member:

"uri": "mongodb://localhost:27022/chat,localhost:27021,localhost:27020"

You should check replica set connection section in the Mongoose documentation.

# mongoose connect secondary replicateSet

<pre>
let url = 'mongodb://mongo01:1001,mongo02:1002/db_name?replicaSet=xxx-replica' 
// 1 

let conn = mongoose.createConnection(url, {user:'xxx', pass:'xxx', autoIndex: false, replset: {readPreference: 'secondary'}});

// 2  

let conn = mongoose.createConnection(url, {user:'xxx', pass:'xxx', autoIndex: false});
let schema =  new mongoose.Schema({},{read:'secondary'});
let model = conn.model(modelName, schema);

//3
let conn = mongoose.createConnection(url, {user:'xxx', pass:'xxx', autoIndex: false};
let schema = new mongoose.Schema({});
let model = conn.model(modelName, schema);
model.find().read('secondary').then(info => {});

</pre>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!