Unable to connect DB cluster with Mongo node driver


We are trying to connect DB cluster via node application and getting the following error

MongoServerSelectionError: Server selection timed out after 30000 ms
    at Timeout._onTimeout (/home/ec2-user/test/node_modules/mongodb/lib/sdam/topology.js:293:38)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(1) {

we tried the solutions provided in forum like

  1. Setting directConnection=true
  2. useUnifiedTopology: true, useNewUrlParser: true, maxIdleTimeMS : 270000, minPoolSize : 2, maxPoolSize : 4
  3. useNewUrlParser: true, useUnifiedTopology: true
  4. useUnifiedTopology: false
  5. Changing the host file for DNS resolution.

All the above options did not work for us.

Node Version we are using is Node v16 and mongo v4.4.
We are successfully connecting to the cluster with mongo shell but not with node code.

Please suggest a solution to resolve the above mentioned issue.
Thank you

Please share the connection strings you used in both cases. I suspect that they are different and that you connect directly to one instance (vs replica set) with mongosh.

Because if you have the error ReplicaSetNoPrimary you will have the same error everywhere. The replica set is in the same state whatever client you use to connect.

Please share your rs.status().


mongo --host clusterurl:27017 --username user --password pwd

node way

we also tried this way without replicaSet

The following does not connect to a replica set

that is why you can connect. Please

See https://www.mongodb.com/docs/v4.4/mongo/#connect-to-a-mongodb-replica-set.

As far as I know

is only for localhost connection.


this my rs.status() response

rs0:PRIMARY> rs.status()
        "set" : "rs0",
        "date" : ISODate("2022-08-03T13:57:43Z"),
        "myState" : 1,
        "members" : [
                        "_id" : 0,
                        "name" : "clusterurl:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "self" : true,
                        "uptime" : 197
        "ok" : 1,
        "operationTime" : Timestamp(1659535063, 1)

We now know that your single node replica set is correct you should try to connect your application again.

However, since you have a single node replica set, I would try without

as you do not have any and I do not know if it can cause issues.

1 Like


Thank you the issue got resolved.

1 Like