首页 > 解决方案 > NodeJS MongoDB ReplicaSetNoPrimary

问题描述

我试图使用nodeJS MongoDB包中的以下内容连接到 MongoDB 集群

const client = require('mongodb').MongoClient
const conn = await client.connect(
  process.env.MONGO_DSN,
  {
    useUnifiedTopology: true,
    ssl: process.env.MONGO_SSL, // true
  },
)

MONGO_DSN变量如下:

mongodb://{USER}:{PASSWORD}@{HOST1}:27017,{HOST2}:27017,{HOST3}:27017/{DB_NAME}?ssl=true&replicaSet={REPLICASET}&authSource=admin&retryWrites=true&w=majority

但是,连接超时并出现错误

MongoServerSelectionError: connection <monitor> to {IP_ADDRESS}:27017 closed
    at Timeout._onTimeout (/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
    at listOnTimeout (internal/timers.js:531:17)
    at processTimers (internal/timers.js:475:7) {
  name: 'MongoServerSelectionError',
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map {
      '{HOST1}:27017' => [ServerDescription],
      '{HOST2}:27017' => [ServerDescription],
      '{HOST3}:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

玩了一会儿,我发现如果我ssl从驱动程序构造函数中删除配置选项并让它从 DSN 查询字符串中推断出来,我可以成功连接:

const client = require('mongodb').MongoClient
const conn = await client.connect(
  process.env.MONGO_DSN,
  {
    useUnifiedTopology: true,
  },
)

为什么这个配置选项(不确定其他人是否也会影响)会影响连接能力?

是不是因为如果在 DSN 中出现的构造函数中指定了配置选项,那么它会完全忽略 DSN 查询字符串,这意味着某些配置选项将丢失(主副本)?

澄清一下,DSN中的主机没有问题,正常连接数据库没有问题,只有在构造函数中设置了配置。

标签: node.jsmongodb

解决方案


推荐阅读