Unable to connect to MongoDB

Here is the error code I am getting:

(node:1444) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-shard-00-01-uzi93.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]

I have no idea why it is occurring, it didn’t occur before, then I saw that glitch’s IP was not whitelisted. So I run this in glitch’s cmd:

curl https://ifconfig.co/

and then I put the IP on mongodb’s whitelist, same error happens. Can I get some help?

EDIT: My project was connecting perfectly fine until now, even without its IP being in the whitelist,

Don’t set any whitelisted IPs as Glitch container IPs change all of the time. Set your MongoDB database to allow connections from all IPs. Hopefully that should fix your issue!

I did that, still having the issue, I also changed the pass to see if that would make any difference, nope.

EDIT: Also double checked that the URL was fine,

This part suggests the user or password didn’t match.

They do though, I checked like 3 times. And yes, I am using the password of the database not the account.

If your username or password have non-alpha-numeric characters in them (and all the good ones do) they may not be being escaped properly. You could test this assertion with two relatively minor changes:

  1. change the username and password in your connection string to something known to be incorrect; does the error message change?
  2. temporarily change the username and password of your database to something very simple and update the connection string appropriately; does the error message change?

You can also pull your project down to your local machine and test connectivity from there to eliminate Glitch as a possible source of problems.

1 Like

I tried what you suggested me but neither of the methods seemed to work. I made my project non-private, take a look at its code: https://glitch.com/edit/#!/smiling-flyaway?path=server.js:3:35
Also it is not a glitch problem, it threw an error in my machine too. I am suspicious that it may be my code. It worked perfectly fine until I updated some code, I did not change any password or anything.

I just tried your connection string in my test app, and got the same authentication error.

Did you create a database user named thisismyusername and assign it a read-write role? (Not the same as an Admin role)

FYI once you get the connection working … what you have in settings.json should be put into .env and accessed for example process.env.MONGODB_USERNAME (convention is to use caps for key names).

I changed the .json stuff because it contained my password. Also I will put my stuff in .env but I doubt that will do anything.

Okay this is really weird, I rewinded to my old code which just had fewer lines, changed my password to my current one and I no longer was getting the authentication error. I guess I am good for now.

1 Like