L m
L m

Reputation: 671

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

My node app gives me this message "Could not connect to any servers in your MongoDB Atlas cluster. Make sure your current IP address is on your Atlas cluster's IP whitelist".

I've already added my current IP address along with the 0.0.0.0 on the IP whitelist.

Below is a picture of the error message and the code I've written to connect it. I'm new to node.js and mongodb. I looked through all the solutions on here but none of them were able to solve this.

var express = require('express');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');

var app = express();
app.use(bodyparser.json());

mongoose
     .connect("mongodb+srv://<username:password>@my-cluster.mongodb.net/test?retryWrites=true&w=majority", 
     { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
     .then(() => console.log( 'Database Connected' ))
     .catch(err => console.log( err ));

    app.listen(3003)

This is the error I receive after running nodemon.

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
MongooseError [MongooseServerSelectionError]: Could not connect to any servers in your MongoDB Atlas cluster. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/.
    at new MongooseServerSelectionError (C:\Users\anna james\Dropbox\MERN_SHOPPING_LIST\back\node_modules\mongoose\lib\error\serverSelection.js:24:11)
    at NativeConnection.Connection.openUri (C:\Users\anna james\Dropbox\MERN_SHOPPING_LIST\back\node_modules\mongoose\lib\connection.js:823:32)
    at Mongoose.connect (C:\Users\anna james\Dropbox\MERN_SHOPPING_LIST\back\node_modules\mongoose\lib\index.js:333:15)
    at Object.<anonymous> (C:\Users\anna james\Dropbox\MERN_SHOPPING_LIST\back\server.js:9:7)
    at Module._compile (internal/modules/cjs/loader.js:1157:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
    at Module.load (internal/modules/cjs/loader.js:1001:32)
    at Function.Module._load (internal/modules/cjs/loader.js:900:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47 {
  message: "Could not connect to any servers in your MongoDB Atlas cluster. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/.",
  name: 'MongooseServerSelectionError',
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map {
      'cluster1-shard-00-01-m3rzz.mongodb.net:27017' => [ServerDescription],
      'cluster1-shard-00-02-m3rzz.mongodb.net:27017' => [ServerDescription],
      'cluster1-shard-00-00-m3rzz.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  },
  [Symbol(mongoErrorContextSymbol)]: {}
}


Error Message and code

Upvotes: 50

Views: 154215

Answers (30)

shabas 001
shabas 001

Reputation: 421

i was getting this error because i didn't put my connection string in qoute in the .env files

BEFORE: MONGO_URL=mongodb+srv://username:[email protected]/?retryWrites=true&w=majority&appName=ttCluster

solve it by adding double qoute MONGO_URL="mongodb+srv://username:[email protected]/?retryWrites=true&w=majority&appName=ttCluster"

Upvotes: 0

ray
ray

Reputation: 15276

As of 2024 Oct, there seems to be a recent connection issue in Mongoose. The common symptom would be the same as the description in the question, throwing MongooseServerSelectionError despite having whitelisted the IPs.

As mentioned in one of the comments under the issue, the mitigation would be downgrading mongoose from v8.7.0 to v8.5.2.

Upvotes: 11

Abhishek K
Abhishek K

Reputation: 51

I had connected my mobile hotspot to laptop and got this issue in connection to DB.

Turning internet off and back on in phone solved ✅ connection to Atlas IP error 😆 prev.simConnection was connected to other Dimension IP

Db Connection error- mongo.js:65 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/

Upvotes: 0

Baris Senyerli
Baris Senyerli

Reputation: 920

If your server is AWS EC2 then you need to open outgoing rules:

Custom TCP 27015-27017 IPV4 0.0.0.0/0

then your mongo can connect through given ports to atlas servers.

Upvotes: 0

Akash Dev
Akash Dev

Reputation: 257

I was getting the same error. Tried all the above methods. Previously I was doing everything but I was connected to my college wifi the issue resolved as soon as I connected it with my mobile hotspot. I think this happened because of network restrictions or firewall settings in my college's network infrastructure.

Upvotes: 0

ADITYA KUMAR
ADITYA KUMAR

Reputation: 51

It may be based on your internet connection. As I was connected to my institute's wifi, it was always throwing this :

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://www.mongodb.com/docs/atlas/security-whitelist/

Then I connected to my phone internet and boom, mongoDB connected.

Upvotes: 0

Nagaajay k
Nagaajay k

Reputation: 77

Open the database instance enter image description here

Click on the Network access option from the right bar enter image description here

You can see that the Current IP Address has not added. You will not be able to connect to databases from this address.

click on add IP address in the top right corner enter image description here click on ALLOW ACCESS FROM ANYWHERE or type 0.0.0.0/0 in the access list entry and click confirm. Then restart the application or server.

This is for the development environment. In production make sure you add only the required IP address or valid allowed IP address in the access list entry for better privacy and security for private databases. if required or the database is public then you can use the above method.

Even turning off the VPN works sometimes but not all the time. check proxy settings on the laptop. or connected to the public network with a dynamic Connection also causes the problem

Upvotes: 0

Mehedi
Mehedi

Reputation: 607

MongoDB Atlas > Security > Network Access > +Add IP Address > Allow access from anywhere would definitely work, but in reality it is not a safe choice, since you are basically allowing anyone to connect to your db from any IP address (from 0.0.0.0 to 255.255.255.255 i.e. 0.0.0.0/0).

Instead, you can figure out your server public IP address, and then +Add IP Address for that public IP address(es) only as a CIDR range. For example,

  1. say your local machine IP address is 56.12.345.45, you would add 56.12.345.45 or 56.12.345.45/32 to allow connections from your local machine only and not from anywhere else. Find your local machine's pub IP address here: https://whatismyipaddress.com/
  2. say you hosted a test app in a replit server which has a public IP address 45.12.345.67, you may need to add 45.12.345.67/8 to allow connections from 45.0.0.0 - 45.255.255.255 range only and not from anywhere else. (Replit free hosting usually requires this big IP range to be added). You can try to see if a smaller range works for you e.g. 45.12.345.67/24 or 45.12.345.67/16. The smaller & specific the range is the better & secure your db. Find your server's pub IP address using the domain name: https://www.whatsmydns.net/

Upvotes: 0

SH Razo
SH Razo

Reputation: 19

You can try after turning off your VPN.

Upvotes: 0

wajahat12345
wajahat12345

Reputation: 27

remove any proxy or vpn if you are using, then go to network setting > Add new Ip and select Allow access from any where If still not work then again go to network setting > Add new Ip > this time add current Ip Then this will work 110%. If any issue feel free to ask.

Upvotes: 0

Hasi
Hasi

Reputation: 46

If none of the solutions worked for you, check the date and time of your OS. If it is incorrect Atlas refuses the connection but still gives the same error suggesting an IP whitelist.

If you are on WSL, try checking the date and time of the WSL distro as well. It is supposed to sync with Windows but sometimes it gets out of sync. If that's the case you can use the following command to re-sync the WSL clock with the Windows.

sudo hwclock -s

If you can connect with Compass but not with WSL, this is most likely the issue.

Upvotes: 0

Omar Saade
Omar Saade

Reputation: 595

The IP address seen by Atlas is not necessarily the IP address of your workstations. If behind a router that does NAT or using VPN the address seen is the one of the router or the exit point of the VPN.

First try to Allow Access From Anywhere. If it works it is most likely because you whitelisted an IP address that is not your public address. Find your public IP with https://www.whatismyip.com/

If the above does not work then we need more information to help.

Upvotes: 1

hamid saifi
hamid saifi

Reputation: 464

If there is no issue by the end of the MongoDB URI so try disabling the firewall and then connecting the MongoDB it works then you will have to make the MongoDB cluster IP address whitelist and then you can enable the firewall again with no issue.

Upvotes: 0

Naisarg Parmar
Naisarg Parmar

Reputation: 801

If your server is setup in VPC -> Private Subnet. In this case, EC2 is using NAT gateway(which is setup in publicsubnet), so in atlas whitelist, add NAT gateway ip.

Upvotes: 1

Ali Akbar
Ali Akbar

Reputation: 41

Three things I did that solved the issue:

  1. Disabling my firework.
  2. Allowing access of Atlas IP from anywhere. How --> My Network Access > Edit(My IP Address) > set your new IP as 0.0.0.0/0 and confirm.
  3. Updating my password by MongoDB Atlas > Database Access > complete 3 steps in the below images image (credit to @piouson ). Also, copying the updated password to my MongoDB compress and mongooge.connect in the server.js enter image description here

Upvotes: 0

geppy
geppy

Reputation: 121

I had the exact same issue here is an example broken down:

mongodb+srv://<userWithAccessToDB>:<password>@dev-12abc.mongodb.net/<yourDatabaseName>?retryWrites=true&w=majority

  1. Check the username at the spot userWithAccessToDB has access
  2. Check that the password is correct in the password part of the string
  3. Check that the database exists and you are connecting to the correct one in the yourDatabaseName slot
  4. Check that you have the +srv from the beginning of the string

mongodb+srv

Upvotes: 2

Ozer Ozturk
Ozer Ozturk

Reputation: 209

I was able to solve the connection problem to the server on MongoDB by doing this change.

MongoDB Atlas -> NetworkAccess -> Edit -> Allowed Access from Anywhere

Upvotes: 11

Gopala Raja Naika
Gopala Raja Naika

Reputation: 2679

As lakshitha-samod said, it's not only the IP address issue, It may be different

(In my case I was using my login password instead db password)

mongodb+srv://<username>:<password>@<clusterName>.p9ykp.mongodb.net/<databaseName>?retryWrites=true&w=majority

1. IP Address (for cross check)

Go to Network Access -> Add/ Edit ->Add Current IP Address or Allow Access from Anywhere

1. check DB user/ create one

Go to Database access -> create new / edit and reset the password if don't remember

2. Database name

Go to your cluster -> Browse Collections -> select a collection(database name: ex: sample_training)

Upvotes: 2

Gayatri
Gayatri

Reputation: 181

Follow below steps:
1] Go to https://www.mongodb.com/cloud/atlas
2] login to your mongodb atlas account
3] Click on network access

i] if you have already added ip address, then here you can see ip access list
a] click on delete 

ii] if you have not already added ip address, then just follow below steps:

4] click on add ip address
5] select 'add current ip address' or if you want you can also select 'allow access from anywhere'
6] type in comment if you want
7] click on confirm button
8] this will show pending loader, wait until it shows active status
9] now restart your server on terminal by typing 'npm start'

-- That's it!

Upvotes: 17

Francisco Gallo M.
Francisco Gallo M.

Reputation: 327

In your Mongo project, go to the network access section, and edit the IP to allow access from anywhere (0.0.0.0/0). Ensure that strong credentials (username and password) are used for all database users when allowing access from anywhere.

Upvotes: 3

Ashwani Kumar Kushwaha
Ashwani Kumar Kushwaha

Reputation: 171

if you are used any proxy or certificate based internet then this type problem is raise.Try different internet connection.

Upvotes: 1

aflynn
aflynn

Reputation: 47

I struggled with this for so long, then finally thought to check the firewall on my router. I had set it to the highest security level at one point, and set it one level lower instead, and that fixed it!

The default IP address for routers is usually 192.168.0.1, but it may differ in some cases. Just go to that IP, login as admin, and try changing your firewall settings. Of course, there's a trade off of some security, but in my case, this setting was messing up other things as well, such as smart device connectivity.

Upvotes: 1

crispengari
crispengari

Reputation: 9333

If the password is correct and you have allowed access from anywhere and you still getting the same error then, The problem is with your network which has a firewall. I solved my issue by just changing the network because mine was having a firewall.

Upvotes: 8

Modem Rakesh goud
Modem Rakesh goud

Reputation: 1788

Not sure if it is the right reason. But, its working for me when i disconnect the VPN.

When connected to VPN, I'm getting below error message.

Error: "Could not connect to any servers in your MongoDB Atlas cluster. Make sure your current IP address is on your Atlas cluster's IP whitelist".

Upvotes: 9

user14831698
user14831698

Reputation: 19

To whitelist an IP address, go to your target cluster on MongoDB Atlas. Next, go to Network Access under the Security tab. On the IP Whitelist tab, click on Add IP address. Type your IP address manually under Whitelist Entry, then click Confirm. run your code it should run without any problem.

Upvotes: 0

Rafia Zafar
Rafia Zafar

Reputation: 412

Try keeping these questions in mind when you face such an issue with your mongodB that:

Did I changed my IP address before I started working with my mongodb again after a long break? If no, then please change it because usually mongodb removes it after every 6 hours.

Did I moved from the place where I worked last time? If yes, then please change your IP again and activate it.

Please do visit the link https://studio3t.com/knowledge-base/articles/mongodb-atlas-login-ip-whitelisting/#whitelist-multiple-or-additional-ip-addresses and learn more about why you get such error and how deal with them. It helps a lot.

Upvotes: -1

Sasi Kumar M
Sasi Kumar M

Reputation: 2630

At times, it may be due to system settings as well.

In my case it was server system's date & time, it was not updated to current date & time settings, hence the connection to db from the server was refused. Updated the same, and restart the server, connection was successful.

Upvotes: 3

Lakshitha Samod
Lakshitha Samod

Reputation: 391

It's not always problem with the ip. Can have problem in db name , username or password.Then also connection failed.

Upvotes: 5

Vighnesh Kulkarni
Vighnesh Kulkarni

Reputation: 1019

Try doing this:- MongoDB Atlas -> NetworkAccess -> Edit -> Allow Any

This worked for me!

Upvotes: 90

Ali
Ali

Reputation: 535

Are you using proxy?? please try with different internet connection first.

Upvotes: 31

Related Questions