mongodb

MongoDB: Could not connect to any servers in your MongoDB Atlas cluster.

2021-07-14

If your localhost is not responding, it could be that your IP address is not whitelisted. This blog post will show you the way to whitelist your IP address in MongoDB.

//a.storyblok.com/f/114452/1080x608/f0f1d42a22/mongodb.png

Howdy👋 I'm Arisa, a DevRel Engineer at Storyblok.

When you work on a project with MongoDB, you might encounter this error.

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
    at NativeConnection.Connection.openUri

Well, it's actually not that complicated as the error log shows. Let's dive in to solve it!

The environment

Here is some info about my environment.

  • Node.js

  • MongoDB

  • nodemon

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "lodash": "^4.17.21",
    "mongoose": "^5.13.2",
    "morgan": "^1.10.0"
  }
}

What did I do at that moment?

Just ran nodemon app to run a localhost. It was supposed to display the results in the browser but it didn't with the error log above.

Solution

Go to Network Access in Security section.

Click + Add IP Address button.

Click Add current IP address.

Access your localhost and hooray!🎉 You should be able to access your results in the browser.

A note

There's an option with Allow access from anywhere from the screenshot. If you're working on just testing something, it could be an option but I do not recommend using it for production use.

Summary

I hope you found something useful to solve what you got stuck. Let me know if there's something you find new or a better approach!

Ciao✌️