首页 > 解决方案 > 找不到NodeJs Mongodb连接问题副本集

问题描述

当我尝试打开与 MongoDB 副本集的远程(公共 IP)连接时遇到问题。使用笔记本电脑上的 mongo shell,我可以打开连接,但使用 nodejs 我收到错误“MongoError: no primary found in replicaset or invalid replica set name”。

NodeJs(v11.4.0 - mongo lib:3.1.10)

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://test:XXXXX@mongo0:27017,mongo1:27017/mydb', {useNewUrlParser: true, replicaSet: "rstest"}); 

输出:

node:1050) UnhandledPromiseRejectionWarning: MongoError: no primary found in replicaset or invalid replica set name
at /node_modules/mongodb-core/lib/topologies/replset.js:636:11
at Server.<anonymous> (/node_modules/mongodb-core/lib/topologies/replset.js:357:9)
at Object.onceWrapper (events.js:277:13)
at Server.emit (events.js:189:13)
at /node_modules/mongodb-core/lib/topologies/server.js:508:16
at /node_modules/mongodb-core/lib/connection/pool.js:532:18
at process.internalTickCallback (internal/process/next_tick.js:70:11)
(node:1050) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1050) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Mongo Shell(MongoDB shell 版本 v4.0.4):

mongo -u "test" -p 'XXXXX' 'mongodb://mongo0:27017,mongo1:27017/mydb?replicaSet=rstest'

输出:

MongoDB shell version v4.0.4
connecting to: mongodb://mongo1:27017,mongo0:27017/mydb?replicaSet=rstest
2018-12-14T12:39:38.536+0000 I NETWORK  [js] Starting new replica set monitor for rstest/mongo1:27017,mongo0:27017
2018-12-14T12:39:38.646+0000 I NETWORK  [ReplicaSetMonitor-TaskExecutor]  Successfully connected to mongo1:27017 (1 connections now open to mongo1:27017 with a 5 second timeout)
2018-12-14T12:39:38.649+0000 I NETWORK  [js] Successfully connected to mongo0:27017 (1 connections now open to mongo0:27017 with a 5 second timeout)
WARNING: No implicit session: Logical Sessions are only supported on  server versions 3.6 and greater.
Implicit session: dummy session
MongoDB server version: 3.4.4
WARNING: shell and server versions do not match
rstest:PRIMARY> 

也许是我做错了什么......

编辑:我也尝试过使用 python 的 pymongo 并且效果很好。另一件事是使用 nodejs,我需要在我的 /etc/hosts 中设置 mongo arbitrer 的 IP,但不需要使用 mongo shell 和 pymongo。

谢谢

标签: node.jsmongodb

解决方案


嗯,最后我找到了。我在 /etc/hosts 中犯了一个错误。Mongo0 有 Mongo1 的公共 IP,Mongo1 有 Mongo0 的公共 IP。奇怪的是,python 和 mongo shell 并没有抱怨它,但 Nodejs 是的。


推荐阅读