简体   繁体   中英

MongoDB connection error from NodeJS backend using mongoose

I have deployed a mongodb replicaset which I am trying to connect to using a node js backend application. My connection code is as follows:

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' is the connection URL which I have put together using the mongodb documentation and is the following:

  database: "mongodb://user:pw@xxx.eu-west-1.compute.amazonaws.com:27017,xxx.eu-west-1.compute.amazonaws.com:27017,xxx.eu-west-1.compute.amazonaws.com:27017/db7_0?replicaSet=rs0"

Note: 'user', 'pw' and 'xxx' are just placeholders for the real details which I have used in the connection string.

When I start up the server and the database connection is created, my logs show the following: 在此处输入图片说明

And my application is throwing the following 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

I've tried many different approaches to fixing the issue, such as specifying the user, password and database in the connection string as well as the mongoose.connect parameters and this did not make any difference. I was initially on Mongoose v5.9.2 (now v5.8.2) and the behaviour is still the same.

Also, please note that running the following in the command prompt does work:

mongo "mongodb://user:pw@xx.xx.xxx.xx:27017/db7_0"

So i suspect it might be a mongoose error however I am struggling to figure out the issue.

It turns out that my issue was caused by the configuration of the replicaSet. I had configured each of the members of the replicaSet using the ipv6 address of each member, which was not allowing me to connect to the replica set for some reason. I then reconfigured the replica set and changed each host address to the public DNS ipv4 address of each member and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM