36

So I'm currently wirting a web application and I need database so I decided to go with mongodb and mongoose. Until now I tested everything on localhost and it worked but I wanted to move the data to a server. I had heard of Atlas and registered myself and "uploaded" the data.

Now I want to connect to the cluster via a node.js app.

mongoose.connect('mongodb+srv://engllucas:p%40ssw0rd@insight-quhku.mongodb.net/test');

I got the string of the mongodb Atlas site at the point Connect Your Application

Then I swapped my password.

mongoose.connect('mongodb://engllucas:p%40ssw0rd@insight-quhku.mongodb.net/test');

This didn't work either.

Thats the error message:

{ MongoError: failed to connect to server [insight-shard-00-02-quhku.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 18.194.163.64:27017]
at Pool.<anonymous> (U:\WEBT\ProjectInsight\Quiz\node_modules\mongodb-core\lib\topologies\server.js:503:11)
at emitOne (events.js:115:13)
at Pool.emit (events.js:210:7)
at Connection.<anonymous> (U:\WEBT\ProjectInsight\Quiz\node_modules\mongodb-core\lib\connection\pool.js:326:12)
at Object.onceWrapper (events.js:318:30)
at emitTwo (events.js:125:13)
at Connection.emit (events.js:213:7)
at TLSSocket.<anonymous> (U:\WEBT\ProjectInsight\Quiz\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:316:30)
at emitOne (events.js:115:13)
at TLSSocket.emit (events.js:210:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoNetworkError',

message: 'failed to connect to server [insight-shard-00-02-quhku.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 18.194.163.64:27017]' } (node:4920) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [insight-shard-00-02-quhku.mongodb.net:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 18.194.163.64:27017] (node:4920) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Lucas Engleder
  • 661
  • 1
  • 6
  • 18

24 Answers24

82

I also had a similar issue, and I was able to solve it by adding my white-listing my IP address under Clusters -> security -> IP Whitelist. Instead of clicking my current ip address, just search what's my ip on google and paste that instead. I hope it works!

Waweru Kamau
  • 1,429
  • 14
  • 20
  • 9
    pathetic exception from mongodb not showing proper message what is the problem .Thanks your answer works – sarir Jan 06 '20 at 16:42
  • 3
    I tried this but I'm still not able to get a response – Rogelio Aug 26 '20 at 07:19
  • The above solution works and if it still doesn't work then try to disable your Antivirus and try again. – Jitender Kumar Sep 12 '20 at 12:02
  • 1
    I used that "use my current ip" option while adding ip to mongodb whitelist, then worked. But your answer helped me to unserstand the issue was ip and not my code. – K. Shaikh May 16 '21 at 14:42
27

I have had this issue connecting to a MongoDB Atlas cluster. I have had to resolve this issue twice because I was working on a project from two different computers (a Macbook Pro and a Windows PC).

Here is my comprehensive answer for everything that I have figured out to resolve the issue of my application not connecting to the cluster.

First Make sure your IP is whitelisted like the above suggestions. The easiest solution is the "All IPs" whitelist of 0.0.0.0/0

Second Check your VPN if you are using one. I was trying to connect to the cluster while connected to a VPN. Once I turned off my VPN, I was able to connect.

Third Make sure your internet settings are not preventing you from connecting to the cluster. My home Xfinity wifi security settings were set too high and this was preventing the connection. I think the router was not allowing a connection to port 27017. One way to test if this issue is occurring is to tether your computer to your phone for internet instead of your wifi and try connecting. I was able to connect using my iPhone as a hotspot for internet. I reset my router to factory settings which fixed the issue.

prestondoris
  • 339
  • 4
  • 11
  • The Third solution worked for me. It was infact my wifi security settings, and it worked for me after I switched to the phone hotspot. Thanks for this @prestondoris – codePrady Aug 17 '19 at 07:47
  • The Third solution worked for me too. After I connected to my phone hotspot, I was able to connect to my Atlas server. – Sriram Sridharan Nov 13 '19 at 01:54
  • Glad this worked for you both. I was beating my head against a wall for about a month trying to figure out what my issue was. – prestondoris Jan 10 '20 at 17:47
  • I was able to connect a day before, with mobile usb tethering, but the same connection didn t work for me today. First solution worked for me. Will there be any security issues? I am using it for my personal projects , to learn mongodb. Thanks! – Arpan Banerjee May 17 '20 at 06:41
  • I have a problem with the second point. When disconnected to VPN I am able to connect and when connected to VPN it is throwing an error. – Anand Vaidya Jul 01 '21 at 16:48
6

if you are using mongoose previous to version 5.0.15:

the mongodb+srv:// uri is not valid to the underlying native driver.

just removing the +srv will not work either, as the uri will need to include your replica hosts and the replicaSet/authSource parameters.

you can either

1. Upgrade to mongoose 5.0.15 and use the shorter +srv format

or

2. Use your current version with the full uri from your Atlas cluster dashboard, selecting the older driver (see Note below) version uri.

from your cluster dashboard, press the connect button, then (assuming you have whitelisted your node server's IP ) select "connect your application", then press "I am using 3.4 driver or older". Use the resulting uri string substituting your password.

Note: In the dialog for choosing your URI string in the connect helper on the Atlas cluster dashboard, it says "I am using driver 3.* or (newer|older)". This is a poor choice of words, as the 3.6 and 3.4 don't refer to the driver version, but the server version. Further, using one version of the server or the other has nothing to do with the driver being used to connect, which is where the actual dependency lies that determines which version of the URI to use.

lineus
  • 698
  • 4
  • 7
  • Probably worth a note that this is a dependency on the 3.x series of the node driver, which only the updated mongoose releases actually use. Does the atlas dashboard actually say *""I am using 3.4 driver or older".*? Because if that's the text related to the node driver it's a little misleading since the current driver release is `3.0.6` and not `3.4`. – Neil Lunn Apr 18 '18 at 09:19
  • yeah, it asks you to choose between "3.6 or newer" and "3.4 or older". It's weird. From what I could discern in the docs that are linked to from the connect your app dialog... the 3.6 and 3.4 refer to the version of MongoDB as opposed to the driver: https://docs.atlas.mongodb.com/driver-connection/ ( the tabs on this page explicitly say MongoDB Server 3.{6,4} ) – lineus Apr 18 '18 at 09:34
  • I presumed that `3.4` did refer to **server**, and that's why I questioned that the text actually says ***driver*** as you quoted. So it does not actually say **driver** at all, and that's just a misquote in your answer. Understand now? – Neil Lunn Apr 18 '18 at 09:36
  • it does say 'I am using driver 3.4 or earlier' here is a screenshot of the dialog; https://www.dropbox.com/s/v7dwlfpx1ymqpjy/Screen%20Shot%202018-04-18%20at%205.37.38%20AM.png?dl=0 so I guess it was a misquote in my comment, not my answer :) – lineus Apr 18 '18 at 09:38
  • Okay then. Either way, it's wrong. Hence the clarification on where the actual dependency is. – Neil Lunn Apr 18 '18 at 09:45
  • Thanks for the input Neil! Updated the answer. I also filed an issue with atlas support to update the button text :) – lineus Apr 18 '18 at 10:33
  • The thing is my mongoose version was up to date. I tried to reinstall it and tested it again but now i get errors still talking about the @ and other special characters in the password. Is there any character that's special but still not used in any way – Lucas Engleder Apr 21 '18 at 16:06
  • You’ll need to uri encode your password variable before adding it into the uri string. EncodeURI(passwd) should work. I’m mobile at the moment but I can look into it further when I’m back at my desk soon. – lineus Apr 21 '18 at 16:58
  • var uri = 'pa§§word1'; var res = encodeURI(uri); mongoose.connect('mongodb+srv://engllucas:' + res + '@insight-quhku.mongodb.net/test'); Still doesnt work – Lucas Engleder Apr 21 '18 at 21:21
  • Try encodeURIComponent instead, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent – lineus Apr 21 '18 at 22:13
  • I tried this var but its still working var uri = 'pa&&w0rd'; var res = encodeURIComponent(uri); mongoose.connect('mongodb+srv://engllucas:' + res + '@insight-quhku.mongodb.net/test'); – Lucas Engleder Apr 24 '18 at 14:48
  • You saved my day!! Thanks a lot. removed old mongoose from package.json and reinstalled latest one and it got connected to Mongo Atlas!! – rohitpaniker Jul 19 '19 at 09:22
4

It's an issue of your "IP Whitelist". Edit and update it once, it should work fine then.

Sohan
  • 558
  • 6
  • 17
4

Above answer is right but just i want to added one point:

From security perspective it is not good;

  1. I also had a similar issue, and I was able to solve it by adding my white-listing my IP address under Clusters -> security -> IP Whitelist. Instead of clicking my current ip address, just search what's my ip on google and paste that instead. I hope it works!

  2. I also had a similar issue, and I was able to solve it by adding my white-listing my IP address under Clusters -> security -> IP Whitelist. added this IP in list: 0.0.0.0/0 it will open to all.

Pramod Kharade
  • 2,005
  • 1
  • 22
  • 41
3

I ended up resolving this issue by simply including "+srv" to the beginning of the connection string like so:

mongoose.connect("mongodb+srv://<username>:<password>@<address>/<database>?retryWrites=true&w=majority", {useNewUrlParser: true});

Which is weird because I found several answers instructing me to do the contrary. I guess I got my versions of mongoose mixed up.

Hope this helps someone.

grodd100
  • 31
  • 1
2

I also faced the similar issue while I was connecting MongoDB Compass to https://cloud.mongodb.com/ cluster.

The following steps resolve the issue.

  1. Visit google.com > Enter My IP Address > Copy the Public IP Address of your system/network
  2. Go to https://cloud.mongodb.com/ Cluster > Select Security > Network Access > Click on IP whilelist Tab > Add IP Address > Enter your public IP address.
Mukesh Arora
  • 1,763
  • 2
  • 8
  • 19
2

If you are connected to a hotspot and feels you have done everything correctly, disconnect and reconnect. Most especially switch off your internet connection and reconnect.

Ib Abayomi Alli
  • 361
  • 3
  • 6
1

Apparently, changing

mongoose.connect(keys.mongoURI);

to

mongoose.connect(keys.mongoURI, () => { }, { useNewUrlParser: true })
    .catch(err => {
        console.log(err);
    });

worked for me.

1

Check that your current IP address is on the MongoAtlas IP whitelist. I came across this problem after I updated my VPN.

1

I was getting that problem and I fixed it. Below is the steps that I used:

  1. First of all add new user in mongodb (Security > Database Access > ADD NEW USER > )
  2. then write to .env file new username and password.
  3. Kill the server and rerun the server.

This is the solution that worked for me.

Rick
  • 1,177
  • 1
  • 19
  • 27
Emre Mutlu
  • 39
  • 1
  • 5
1

I too had this similar issue. then changed

mongoose.connect(db, () => { }, { useNewUrlParser: true })
    .catch(err => {console.log(err);});

but produced error,

(node:5796) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.

then changed the code to

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }, () => { })
        .catch(err => console.log(err));

This worked for me.

kedar sedai
  • 1,687
  • 3
  • 16
  • 25
1
  • I also got the same error and i tried this one logic.
  • Apart from this in mongoDb atlas in netwrok Access , confirgure all ip address.And set it to ---------------- 0.0.0.0/0
1

I had the same problem, adding to white list and other solutions didn't help. But after I created another user. When creating a new user in the "Database User Privileges" field, I selected "Atlas admin" instead of default "Read and write to any database". After that, the connection worked

0

google => my ip adress => copyit

got to Atlas => Once you re in the Clusters Tab, check at the left side=> Security => NetWork Access => Edit Ip => paste the ip adress.

rerun your server and it should be working :)

Yassine Ab
  • 95
  • 1
  • 9
0

I had same problem, while IP whitelisting was set correctly!

The reason was, that MongoDB Enterprise Atlas requires SSL excryption layer trying to connect without that, produces non-reasonable and not self explanatory error like:

Failed to connect to mongodb-m0-nnxxx.mongodb.net:27017
No chance to Authorize

Trying to connect using mondodb client with IP whitelisting being the problem, error message like this is appearing:

mongo "mongodb+srv://mongodb-m0-nnxxx.mongodb.net/test" --username admin

DBClientConnection failed to receive message from mongodb-m0-shard-00-00-nnxxx.mongodb.net.:27017 - HostUnreachable: Connection closed by peer
Unable to reach primary for set mongodb-m0-shard-0
Cannot reach any nodes for set mongodb-m0-shard-0. Please check network connectivity and the status of the set. This has happened for 5 checks in a row.

For example using Robo 3T client, the checkbox "Use SSL Protocol" must be enabled, and **Authentication Method: Self-Signed Certificate **

Test produces Diagnostic output:

v Connected to mongodb-m0-nnxxx.mongodb.net:27017 via SSL tunnel
v Authorized on admin database as admin

Hope this helps somebody.

Arunas Bartisius
  • 1,879
  • 22
  • 23
0

I connected with vpn before I realized it. When I tried to connect to db later, I couldn't do it. I opened my own rope and all permissions in the permissions again. Then when I connected with vpm again, I was able to connect.

Ali Bulut
  • 194
  • 1
  • 8
0

Weird but changing password(one without special symbols) of cluster helped.

0

After numerous troubleshooting steps, I used my cell phone to tether to my computer to see if the issue was my ISP gateway. I was able to connect with no problems connecting with my phone. At that point, I knew it was an ISP issue. To connect using your ISP's internet, you have to open port 27017 on your gateway device. Search 'port forwarding' for your particular ISP to add port 27017 to the list of available ports. It's not open by default for some ISPs like mine. Good coding!

brohjoe
  • 854
  • 4
  • 17
  • 39
0

if you are using aws console then, in the security group of your instance running, set inbound and outbound rule, set custom tcp for port 27017

0

If you are a university student, you may not be able to connect to MongoDB Atlas because your university network has it blocklisted (just like multiplayer games). So if you have not tried yet, probably disconnect from the university internet network and test with mobile data via hotspot.

This solution worked for me (I am staying at IIT Bombay)

Saurabh Mahra
  • 330
  • 5
  • 10
0

the problem for me is that I was trying to create some seed data with the dropDatabase option set to true, and the privileges for the database user were read and write only.

After much research, I was able to fix the problem by giving the user custom rules from Database Access -> Edit -the user bar- -> Specific Privileges -> dbAdminAnyDatabase or dbAdmin and you specify the database.

-1

I had a similar issue and wasn't able to connect to mongo. Apparently mongodb didn't like my password which contained special characters. I tried doing URL encoding and all other kinds of manipulations, but what proved to solved the issue for me eventually was simply changing the password to one that doesn't use special characters. I used the mongodb password generator and all works fine now.

vrommer
  • 19
  • 1
  • 3
-1

If EveryOther options above mentioned failed, This is what I did

Just Made my Wifi Network to "PUBLIC" from "PRIVATE".

this fixed the last issue too

Jay
  • 336
  • 1
  • 4
  • 15