node.js Mongoose 连接到副本集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24396583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:32:13  来源:igfitidea点击:

Mongoose connection to replica set

node.jsmongodbmongoosereplicaset

提问by lor1an

I tried to connect to MongoDB replicaSet via mongoose. I used this link.
Configuration json:

我试图通过猫鼬连接到 MongoDB replicaSet。我用过这个链接
配置json:

"mongoose": {
   "uri": "mongodb://localhost:27022/chat,localhost:27021,localhost:27020",
   "options": {
       "replset": { "rs_name": "rs0" },
       "server": {
           "poolSize": 3,
           "socketOptions": {
               "keepAlive": 1
           }
       }
    }
}

Mongoose connect:

猫鼬连接:

var mongoose = require('mongoose');
mongoose.connect(config.get('mongoose:uri'), config.get('mongoose:options'));

And after launching application i got exception:

启动应用程序后,我得到了异常:

Error: host must be specified [undefined]
at new exports.ConnectionPool (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:18:11)
at Server.connect (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\mongodb\lib\mongodb\connection\server.js:335:25)
at Db.open (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\mongodb\lib\mongodb\db.js:264:23)
at MongoStore._open_database (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect-mongo\lib\connect-mongo.js:174:15)
at MongoStore._get_collection (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect-mongo\lib\connect-mongo.js:169:14)
at MongoStore.get (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect-mongo\lib\connect-mongo.js:213:10)
at Object.session [as handle] (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect\node_modules\express-session\index.js:215:11)
at next (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect\lib\proto.js:194:15)
at Object.module.exports [as handle] (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\middleware\resExtensions.js:21:2)
at next (c:\Users\lor1an\Downloads\prj_chat-master\prj_chat-master\node_modules\connect\lib\proto.js:194:15)

Db: chat, primary server: localhost:27022.

数据库:聊天,主服务器:本地主机:27022。

Also I tried remove two other servers (keeping only the primary one in config json) and I saw that it knows about the secondary servers (I used log). I think it's about mongodb meta-data. But when I shutdown primary one, it finished its work (no wonder), I need it so it can use the secondary one instead.
Any ideas?

我还尝试删除其他两台服务器(仅在 config json 中保留主要服务器),我看到它知道辅助服务器(我使用了日志)。我认为这是关于 mongodb 元数据。但是当我关闭主要的时,它完成了它的工作(难怪),我需要它以便它可以使用次要的。
有任何想法吗?

回答by malix

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

Auto_reconnect 根据https://team.goodeggs.com/reconnecting-to-mongodb-when-mongoose-connect-fails-at-startup-83ca8496ca02关闭

回答by Christian P

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

您的连接字符串可能无效。您应该为每个副本集成员提供 URI:

"uri": "mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/admin?replicaSet=myRepl"

"uri": "mongodb://db0.example.com:27017,db1.example.com:27017,db2.example.com:27017/admin?replicaSet=myRepl"

You should check replica set connectionsection in the Mongoose documentation.

您应该检查Mongoose 文档中的副本集连接部分。

回答by ChrisRich

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).

仅当连接 URI 包含单个非集群连接(也称为单个连接字符串)时,才会调用“服务器”块。

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

“replset”块仅在连接 URL 包含逗号分隔的连接字符串列表(又名复制集)时调用。

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.

此块适用于本地主机和生产环境。希望能帮助到你。

回答by Hyman LI

# 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>