getting ReplicaSetNoPrimary and MongoServerSelectionError error while connecting MongoDB with nodejs
Asked Answered
G

12

24

I am trying to connect to mongodb but getting below error could you please help

var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://usernamexyz:[email protected]:47017/sampleDB?replicaSet=NAME_2436&readPreference=primary&authSource=admin&w=1', { useNewUrlParser: true, useUnifiedTopology: true  })
.then(() => console.log("Mongodb connected"))
.catch(err => console.log(err));

And the error i am getting as below

MongoServerSelectionError: connection <monitor> to 155.30.360.129:37017 closed
    at Timeout._onTimeout (C:\Fintech\NodeFirstApp\node_modules\mongodb\lib\core\sdam\topology.js:448: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 {
      'hostmxy-mw-e6-u1238.nam.nsroot.net:47017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  },
  [Symbol(mongoErrorContextSymbol)]: {}
}
Gurgitation answered 4/2, 2020 at 18:50 Comment(1)
Are you able to connect to the replica-set from the Mongo Shell?Rudderhead
P
30

Go to Mongodb where you created a cluster and under "ipwhitelist" click on the edit IP address button and then choose "Add current IP address"

Picrite answered 17/6, 2020 at 5:8 Comment(0)
B
7

There was a firewall issue for me, and here are the steps i followed:

  1. Search for Windows Firewall with Advanced Security
  2. Select Outbound Rules
  3. Select New Rule
  4. Select Port in Rule Type, Click next
  5. Select TCP and Specific remote ports and write in there 27015-27017
  6. Save the rule This worked for me :)

enter image description here enter image description here

Beshore answered 27/10, 2020 at 4:36 Comment(0)
T
7

I setup replica set on mongod server in order to have oplog facility and use it to sync database programmatically with golang client. It was working fine with local windows server.

mongod.exe --dbpath $dpath --bind_ip 0.0.0.0 --port $port --replSet rs0
mongo.exe' -port $port --eval 'rs.initiate()'

When I used docker it showed me that ReplicaSetNoPrimary Error.

docker run --name mongo21 -d -p 27021:27017 mongo  --bind_ip_all  --replSet rs0
docker container exec mongo21 mongosh --eval 'rs.initiate()' 127.0.0.1

I noticed that perl client as well as Robo3 T, mongosh connected to the server localhost:27021 without problem. mongosh shows which mongo uri it uses:

mongodb://127.0.0.1:27017/test?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.1.9

I found I can specify client option before connect:

clientOpts := options.Client().ApplyURI(uri).SetDirect(true)
client, err := mongo.Connect(ctx, clientOpts)

That option fixed golang client connection issue.

Topminnow answered 16/5, 2022 at 7:16 Comment(2)
you can set clientOpts shorter: clientOpts := options.Client().ApplyURI(uri).SetDirect(true)Topminnow
indeed the direct connection solved it: const client = new MongoClient(url, {directConnection: true});Noncontributory
A
3

Some MongoDB implementations as a service such as IBM Cloud, GCP or AWS might need a certificate to be able to connect. That was my case. The problem was resolved when I added a certificate to the docker file and then passed the parameters as options

let options = {
    tls: true,
    tlsCAFile: `/path/to/cert`,
    useUnifiedTopology: true 
};

// connects to a MongoDB database
MongoClient.connect(connectionString, options) 

Reference https://cloud.ibm.com/docs/databases-for-mongodb?topic=databases-for-mongodb-mongodb-external-app

Annapolis answered 18/5, 2022 at 19:25 Comment(1)
I missed the tls option. Adding the tls and the certificate solved my issue.Sessoms
B
1

I had the same issue with this. It was fixed when I added the current IP address to IP whitelist inside of MongoDB.

Bandler answered 15/5, 2022 at 6:14 Comment(0)
H
0

I was also getting the same error while connecting to MongoDB atlas. You have to do following things. 1. allow outbound port 27015-27017 in firewall in your system. 2. update the latest MongoDB and NodeJs. 3. whitelist your system IP in MongoDB atlas cluster under network access.

It worked for me. I hope it works for you also.

Hydatid answered 3/3, 2020 at 16:54 Comment(0)
B
0

Updating "Network Access" did not work for me. What worked for me was to update "Database Access" by "Autogenerate Secure Password" and make sure to click "Update User" to save new password!

MongoDB Atlas > Database Access > complete 3 steps in image

enter image description here

Bosomed answered 3/2, 2022 at 11:59 Comment(0)
S
0

I was using Atlas Mongo Cluster and using 'mongomirror' I am trying to push the data from one replicaset cluster to another. In the process, I was getting this error..

After ot of research, I understood that, the name of cluster visible in UI should not be used.. instead you need to run the below command

rs.status()

This will give a JSON output which has the RS name and respective primary and secondary node endpoints you need to use.

In my case, for abc-temp-shard-cluster, the cluster name I got by running the above command was something like below

atlas-12avca-shard-0/atlas-12avca-shard-00-00.1aqer5.mongodb.net:27017,atlas-12avca-shard-00-01.1aqer5.mongodb.net:27017,atlas-12avca-shard-00-02.1aqer5.mongodb.net:27017
Saith answered 30/5, 2022 at 11:50 Comment(0)
P
0

try to enable ipv6 support at mongo server using --ipv6 flag

mongod --dbpath="D:/data_path" -replSet rs0 --bind_ip 0.0.0.0,127.0.0.1,localhost,::1 --ipv6
Percent answered 19/2, 2023 at 4:3 Comment(0)
A
0

To build onto existing answers, one possibility is that Atlas filters out connections based on your IP address.

You can enable different connections by going to "Security" > "Network Access", where "Security" is located within the left sidebar of the Atlas website.

Accurate answered 18/5, 2023 at 18:1 Comment(0)
P
0

reason: TopologyDescription { type: 'ReplicaSetNoPrimary',}

2024 i was getting this error, go to network access from side bar and your current IP

Pomology answered 6/3 at 8:11 Comment(0)
S
-2

I had this issue on a public university's wireless network, switched over to my hotspot and the issue resolved

Scaffold answered 1/7, 2023 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.