Fixing MongoServerSelectionError while connecting MongoDB with node.js

Barak Saidoff
3 min readJul 22, 2020

--

type: ‘ReplicaSetNoPrimary’

I recently ran into an issue where my node.js application all of the sudden stopped connecting to my MongoDB Atlas server. I had been on the road and suddenly thought of a feature that I wanted to add to my application. Upon starting my sever, I was getting an error that I had never seen before. My solution to this error was to whitelist my current IP address in the MongoDB cluster where my error was occurring.

Error: type: ‘ReplicaSetNoPrimary’ in my node.js application

Upon starting up my node.js application, my server started, as usual. However, my app timed out when it would then try to connect to my MongoDB cluster. The error was saying name: 'MongoServerSelectionError',
reason: TopologyDescription { type: 'ReplicaSetNoPrimary',
. I had no idea what this meant, so as any programmer would do, I turned to google to seek a solution.

The reason this was happening was that, as mentioned before, I was on the road, meaning I was in a different location than from where my MongoDB server was initially created. My IP address was now different from the one that was registered in my Atlas account. I needed to whitelist my current IP Address to my MongoDB cluster where the error was occurring so that it would connect accordingly. Below I will demonstrate how you can do this in your MongoDB Atlas account.

Whitelist your current IP address in your mongo DB cluster:

With your MongoDB Atlas login credentials, open to your account and find the cluster that where the error message is being triggered.

Next, click on Network Access under the Security tab on the left-hand sidebar. This will take you to the IP Whitelist tab.

Click on Add IP Address in the top-right corner. This will open the Add IP Whitelist Entry dialog.

Click on Add current IP address. MongoDB will automatically detect your current address, then click Confirm.

MongoDB Atlas will take a few minutes to deploy the changes, after which you should be good to go. The IP address that will appear should be the same that appears when you search for it manually, using tools like whatsmyip.org.

I hope this quick fix helped you get your MongoDB server up and running again. Below I will link the resources that helped me solve this issue.

https://docs.atlas.mongodb.com/security-whitelist/

https://studio3t.com/knowledge-base/articles/mongodb-atlas-login-ip-whitelisting/#:~:text=To%20whitelist%20multiple%20IP%20addresses,click%20on%20Add%20IP%20address.

MongoDB Atlas

--

--

Barak Saidoff
Barak Saidoff

Written by Barak Saidoff

A creative Full Stack Developer with an entrepreneurial spirit, proficient at Web Application Development using Git and modern web tools.

Responses (8)