首页 > 解决方案 > 仅在本地主机上出现奇怪的 MongoDB 连接问题

问题描述

我有 3 台服务器运行 MongoDB 副本集,1 台主服务器,1 台辅助服务器,1 台仲裁器。而且我在连接到这个副本集时遇到问题。使用在 localhost 和备用服务器上运行的 test.js 文件进行测试。

这是我的 test.js 文件:

const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://root:password"+
"@mgdb1.mydomain,mgdb2.mydomain/vApp?replicaSet=rs0&authSource=admin";

console.log("Connecting...");
MongoClient.connect(url,(err,client)=>{
  if (err!=null){
    console.log("Error:",err);
    return;
  }

  console.log("Connected.");
  process.exit();
});

奇怪的是它显示 ECONNREFUSED 错误,但不是在副本集中 3 台服务器的 IP,它是我的 ISP 范围内的 IP。那么为什么它在连接后失败?它显示 TCPConnectWrap.afterConnect,是否意味着已经建立连接?

错误是这样的:

Connecting...
(node:1412) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Error: { Error: connect ECONNREFUSED 125.235.4.59:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '125.235.4.59',
  port: 27017 }

编辑

我目前的解决方法是直接连接到主服务器而不使用replicaset=rs0,但是,这不是所需的方式。

标签: node.jsdatabasemongodberror-handlingconnection

解决方案


我发现了问题。在云上的一组机器上创建副本集时,服务器的地址是服务器名称,只有同一服务器 LAN 上的其他机器知道。在办公室的本地主机上,没有这样的服务器名称。

解决方法1:

  • 仅连接到主服务器或辅助服务器

解决方法2:

  • 编辑 /etc/hosts 文件(或 c:\windows\system32\drivers\etc\hosts)
  • 将服务器的名称指向其适当的 IP

推荐阅读