Fixing - MongooseServerSelectionError: Could Not Connect to MongoDB Atlas

Fixing - MongooseServerSelectionError: Could Not Connect to MongoDB Atlas

MongoDB Atlas is a powerful cloud-based database solution, but sometimes developers run into the MongooseServerSelectionError when trying to connect their Node.js application to MongoDB Atlas. If you are seeing this error:

Don't worry! This guide will walk you through the possible reasons and their solutions to get your connection working smoothly.


Solution 1: Whitelist Your IP in MongoDB Atlas

By default, MongoDB Atlas blocks all incoming connections unless they are from a whitelisted IP address.

Steps to Whitelist Your IP:

  1. Log in to MongoDB Atlas and select your database cluster.

  2. Navigate to Network Access under Security.

  3. Click Add IP Address.

  4. Choose one of the following options:

    • Allow Access from Anywhere (0.0.0.0/0) (Not recommended for production, but useful for development.)

    • Manually Add Your Current IP by clicking Add Current IP Address.

  5. Click Confirm & Save.

  6. Restart your Node.js server and try connecting again.


Solution 2: Check Your MongoDB Connection String

Your connection string in .env or index.js should be correct.

Example Connection String:

MONGO_URI="mongodb+srv://your-username:your-password@quizcluster.mongodb.net/quizdb?retryWrites=true&w=majority"

Things to Check:

  • Replace your-username and your-password with your actual MongoDB credentials.

  • Ensure the database name (quizdb) is correct.

  • If your password has special characters like @, !, or #, encode them using URL encoding.


Solution 3: Ensure You Are Using the Right Node.js Version

MongoDB Atlas may not support older versions of Node.js.

Check Your Node.js Version:

node -v

If you are using an outdated version, update to Node.js 16+ using:

npm cache clean -f
npm install -g n
n stable

Solution 4: Enable "TLS/SSL" in MongoDB Atlas

MongoDB Atlas requires TLS/SSL for secure connections.

Steps to Enable TLS/SSL:

  1. Open MongoDB Atlas Dashboard.

  2. Go to Database DeploymentSecurityAdvanced Settings.

  3. Enable TLS/SSL Required.

  4. Save changes and restart your connection.


Solution 5: Restart Your Server & Clear Port

Sometimes, the issue is with the local server or an occupied port.

Restart Nodemon & Free Port 5000:

npx kill-port 5000  # Kills any process using port 5000
nodemon index.js     # Restart the server

Final Step: Restart and Test Your Connection

Once you've applied these fixes, restart your Node.js server:

npm start

or

nodemon index.js

If everything is set up correctly, your MongoDB Atlas connection should now work without errors.

Have you encountered this issue before? Let me know in the comments how you solved it! 😊