[NodeJS后端使用猫鼬的MongoDB连接错误

问题描述 投票:1回答:1

我已经部署了mongodb副本集,我正尝试使用节点js后端应用程序连接到该副本集。我的连接代码如下:

mongoose.connect(config.database, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true,
  dbName:"db7_0",
  user:'****',
  pass:'****'

}).catch(function (err) {
  console.log('The connection to the database could not be established. Error details: ', err);
});

'config.database'是我使用mongodb文档汇总的连接URL,如下:

  database: "mongodb://user:[email protected]:27017,xxx.eu-west-1.compute.amazonaws.com:27017,xxx.eu-west-1.compute.amazonaws.com:27017/db7_0?replicaSet=rs0"

注:'user','pw'和'xxx'只是我在连接字符串中使用的真实详细信息的占位符。

当我启动服务器并创建数据库连接时,我的日志显示以下内容:enter image description here

并且我的应用程序抛出以下MongoNetworkError:

The connection to the database could not be established. Error details:  MongoTimeoutError: Server selection timed out after 30000 ms
    at Timeout._onTimeout (C:\Dev\sc\node_modules\mongoose\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) {
  name: 'MongoTimeoutError',
  [Symbol(mongoErrorContextSymbol)]: {}
}
Database error MongoTimeoutError: Server selection timed out after 30000 ms

我已经尝试了多种解决此问题的方法,例如在连接字符串以及mongoose.connect参数中指定用户,密码和数据库,但这没有任何区别。我最初使用的是Mongoose v5.9.2(现在为v5.8.2),其行为仍然相同。

此外,请注意,在命令提示符下运行以下命令确实有效:

mongo "mongodb://user:[email protected]:27017/db7_0"

所以我怀疑这可能是猫鼬的错误,但我正在努力找出问题所在。

node.js mongodb mongoose replicaset
1个回答
0
投票

事实证明,我的问题是由副本集的配置引起的。我已经使用每个成员的ipv6地址配置了副本集的每个成员,由于某种原因,这不允许我连接到副本集。然后,我重新配置了副本集,并将每个主机地址更改为每个成员的公共DNS ipv4地址,并且它可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.