104

I'm trying to connect to my mongoDB server via the connection string given to me by mongo:

"mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true"

In my code I am calling the connection through mongoose like this (obviously putting in my password):

const mongoose = require('mongoose');
const db = 'mongodb+srv://david:<password>@cluster0-re3gq.mongodb.net/test?retryWrites=true'
mongoose
    .connect(db, { 
        useNewUrlParser: true,
        useCreateIndex: true
      })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err));

When I run the code I am getting the following error

"MongoError: bad auth Authentication failed."

Any ideas of what that could mean?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Djaenike
  • 1,645
  • 5
  • 21
  • 32
  • 1
    I guess it should a dot after cluster0 instead of a dash `"mongodb+srv://david:password@cluster0.re3gq.mongodb.net/test?retryWrites=true"` – YoussefDir Nov 09 '21 at 13:06

34 Answers34

204

I had the same problem, and in my case, the answer was as simple as removing the angle brackets "<"and ">" around <password>. I had been trying: my_login_id:<my_password>, when it should have been my_login_id:my_password.

Crowdpleasr
  • 3,574
  • 4
  • 21
  • 37
151

I think you're confused with the mongodb account password and user password. You should use user password, not account password. That was the reason of my case.

vhurryharry
  • 1,875
  • 1
  • 10
  • 28
  • 1
    How can I find out my user password in case I forgot it? – Isaac Michaan Jan 23 '20 at 14:42
  • I don't think you can, Just change it if you forget. You don't need the user password to change your your password solong as you're logged in with your normal account. I think they don't allow you to see it for security reason – Ecks Dee Jul 10 '20 at 20:16
  • Also for the main question, In my the user password I entered was just wrong so if the answer given by @Harry didn't help check that the user password you used your code is correct if you're sure you're not using your account password with a user login (not account) – Ecks Dee Jul 10 '20 at 20:18
  • The password needs to be URL Encoded, if in case there are special characters. e.g. **P@ssw0rd#1** will become **P%40ssw0rd%231** – Lovjith May 27 '21 at 14:38
  • you are the best! Thank you. Actually I didn't enter account password but I entered wrong password for db. I confused after read this I realized. – gurkan Nov 22 '21 at 09:11
  • This was very helpful. The documentation is poor. I didn't realize there were two different sets of passwords. – London804 Dec 15 '22 at 21:12
96

It happens because your provided password in connection string is wrong and most probably you have mistaken cluster password with your login password, in simple words while connecting with Atlas Cluster we can't use our account password by which we login to the Atlas website. In both case we can reset our cluster password and solve this issue.

To Solve The Issue Follow Below Given Steps

Step 1:- Click Database Access From left Side Navigation of MongoDB Atlas page.

Step 2:- Select your username and and click on the edit button from right side.

Step 3:- Click to change password.

Step 4:- Click update user.

While changing password try to keep password only alphabetical because special characters need encoding. See The Image For Your Better Understanding

that's all now you can connect.

Pawan Bishnoi
  • 1,759
  • 8
  • 19
  • Great answer, the issue for me was that I used special characters for my password (like I do for all my passwords). Mongo should give a better error message. – Aditya Garg Oct 07 '20 at 21:23
  • My problem was not only using the incorrect password ( I was using the account password instead of the user password ( as greatly showed in this answer ) ) but I was also using the "<" and ">" on the password and database name. Thank you for the greatly detailed answer. – Dr4kk0nnys Feb 08 '21 at 15:27
  • 1
    Edits that remove fluff [are fine](https://meta.stackoverflow.com/q/260776/6296561). Please refrain from further rollbacks. – Zoe Dec 05 '21 at 16:17
  • Gotcha ! Great answer Pawan :) <3 – Sumit Dec 04 '22 at 06:49
13

Don't use creds in the URI, use like this instead:

mongoose.connect(mongodb+srv://clusterAnything.mongodb.net/test?retryWrites=true&w=majority, { user: process.env.MONGO_USER, pass: process.env.MONGO_PASSWORD, useNewUrlParser: true, useUnifiedTopology: true })
Nimantha
  • 6,405
  • 6
  • 28
  • 69
skipper_dev
  • 173
  • 1
  • 4
11

In my case left and right characters are there

like this:

<Password>

so changed to:

Password
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Gv Ravi
  • 333
  • 2
  • 5
7

Checklist to follow:

1) Make sure you're using the correct password (the DB user password and not the Mongo account).

2) When entering your password, make sure all special characters are URL encoded (for example: p@ssword should be p%40ssword).

3) If you don't remember your password of your DB user - go to Database Access (if you're using Mongo Atlas) -> select your DB user -> edit -> create a new password -> don't forget update to click on 'Update User'.

(!) Security warning: Do not write the password in plain text inside your code - Follow the suggestions given here.

Rot-man
  • 18,045
  • 12
  • 118
  • 124
5

Are you writing your password in the place of <password>? If your aren't, a good practice is to create a environment variable on your operating system and call it using process.env.[your variable]. Ex:

const password = process.env.YOURPASSWORDVARIABLE
const db = 'mongodb+srv://david:'+password+'@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Better yet, you can also put your whole url connection string inside a env variable:

ardmont
  • 105
  • 8
  • Thanks, how would i pass a string into the YOURPASSWORDVARIABLE? – Djaenike Apr 15 '19 at 19:15
  • 1
    You will set your environment variable on your operating system. How you will do this will depend of what OS your are using, and you need to search for how you will do this on your OS. But for now, to make your code run, just place your actual password instead of ``. – ardmont Apr 15 '19 at 19:54
  • 1
    There are other ways of creating env variables besides to do it on you OS. I reccomend you to read [this article](https://medium.com/the-node-js-collection/making-your-node-js-work-everywhere-with-environment-variables-2da8cdf6e786). – ardmont Apr 15 '19 at 19:58
4

Adding to above answers, the issue seemed to revolve around a wrong Database password input for me, because of a distortion of what i read as my current password from the Atlas menu and what MongoDB Atlas really saved as my current password.

There seems to be a "bug" when using the "Copy" button when choosing a new password.

What helped me was the following:

  • Open Atlas in the web
  • Go to "Database Access"
  • Click "Edit" on the Database user
  • Choose "Password" for authentication method
  • Click "Edit Password"
  • Click "Show" in the password field
  • Click "Autogenerate Secure Password"
  • DO NOT press "Copy" button to copy, but use manual selection via mouse and copy the text via right-click of your mouse or keyboard command
  • Click "Update User" below

Then: Go through the list of Database users to make sure that no other Database user has the same password you just newly generated.

Now try your Username/Password combination again using this connection string (leaving out the placeholder characters '$' and '[]':

'mongodb+srv://$[username]:$[password]@$[hostlist]/$[database]?retryWrites=true'


I noticed that when I autogenerated a new password by clicking and then clicking the "Copy" button, that the autogenerated password was reset to the old password. Therefore I assumed the new autogenerated password is correct, but in reality it was my old password, which in addition was the same as for another Database user. I could not comprehend that until I clicked "Show" on the password input field.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
phpaul89
  • 101
  • 6
3

Not only the password

Check all the fields it could be the password the user or the database. If you misspelt any of these you will have an authentication error.
Go to the database access on the left pane under security: enter image description here

And in case change the password using edit button. Let's say your password is: P@sW0rd You can compile the URL using the information contained in the Database Users screen:

client = MongoClient("mongodb+srv://giac:P@sW0rd@cluster0.wjdtk.mongodb.net/testc?retryWrites=true&w=majority")

The other answers did not say that even if you mispell the database name you have a authentication error.

G M
  • 20,759
  • 10
  • 81
  • 84
3

This worked for me

    mongoose.connect(
    `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASS}@cluster0.adv0t.mongodb.net/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority`,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  );

Create a ".env" file (you need to install dotenv before this ) in the parent directory(if you choose a custom location, add the following in server.js / app.js).

require('dotenv').config({ path: '/custom/path/to/.env' }) //uses custom location

Otherwise, add this in the server.js / app.js (the one that initiates server).

require('dotenv').config() //uses default location

In the ".env" file, define the user, password and database like this

MONGO_USER=uSerName
MONGO_PASS=p@sSW0rd
MONGO_DATABASE=myDatabase
rhythmo
  • 859
  • 2
  • 9
  • 21
2

Just remove the angle brackets from both sides of your password.

Wrong Answer :
const db = 'mongodb+srv://username:<password>@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Correct Answer :
const db = 'mongodb+srv://username:password@cluster0-re3gq.mongodb.net/test?retryWrites=true'

Farid Vatani
  • 626
  • 1
  • 7
  • 24
BiplabRoy
  • 21
  • 2
2

I faced a similar issue, weirdly enough it got resolved when I created a new user in database access. This time though I clicked on autogenerate password. It should not matter but in my case it solved the issue.

Vimath
  • 63
  • 8
  • Yup, same for me. They must be blocking "easy to answer" passwords on the authentication layer. Auto-generating the password worked for me too +1 – diogo.silva Mar 08 '21 at 12:36
2

I forgot to update the user after generating and copying the password and was wondering why it wasn't working. I saw the update button later. I was not visible to me earlier. lol. Solved the problem.

Database Access => edit user => generate/copy password => update it! It worked for me.

remember to make sure you have updated it.

dpthegrey
  • 117
  • 10
2
mongodb+srv://janz95:<password>@cluster0.kxus1fg.mongodb.net/test

replace <password> with your password.

mongodb+srv://janz95:janzcoolboy@cluster0.kxus1fg.mongodb.net/test

I'm using alphabetical password in this case. Hope this help...

Januar
  • 49
  • 6
1

Finally, it worked for me to used that connection string with a lower grade that NodeJs versions(2.2.12 or later) cluster url. And After that make sure you have to whitelist your current IP Address from Atlas MongoDB. It should display like 0.0.0.0/0 (includes your current IP address) in Network Access section in Atlas MongoDB. Connect to cluster NodeJs version 2.2.12 or later

And the main issue was where I am storing that connection string url in a constant that part. So initially,I was storing that connection string value in single/double quote but every time I was getting Authentication failure error as it was unable to parse that "Password" value from Atlas mongoDB . So I used backtick (``)instead of single/double quote to store that connection string.

Sample code where I am connecting mongoDB Atlas through a NodeJs application.

const DB_USER = 'your username in atlas mongodb';

const PASSWORD = encodeURIComponent('your password in atlas mongodb');

const url = `mongodb://${DB_USER}:${PASSWORD}@cluster0-shard-00-00.3ytbz.mongodb.net:27017,cluster0-shard-00-01.3ytbz.mongodb.net:27017,cluster0-shard-00-02.3ytbz.mongodb.net:27017/sample-db?ssl=true&replicaSet=atlas-z26ao5-shard-0&authSource=admin&retryWrites=true&w=majority`;

mongoose.connect(url,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: true
  })
  .then(() => {
    console.log('Connected to database !!');
  })
  .catch((err)=>{
    console.log('Connection failed !!'+ err.message);
  });
  • This gives me the following : { MongoNetworkError: failed to connect to server [cluster0-shard-00-02.1jykx.mongodb.net:27017] on first connect [MongoError: bad auth : Authentication failed.] – cyruslk Dec 03 '20 at 19:53
1

I just had this problem knowing that I was using the correct username, password and DBname.

I tried to change the password for the db user to double check, but it still didn't work.

I then instead created a new user, gave the user admin role, set the password etc, and then used that new user and password (same dbname) for the connection and it worked.

I don't know exactly what the issue was, but hoping it can help some of you save some time :)

Dharman
  • 30,962
  • 25
  • 85
  • 135
IndustryDesigns
  • 1,938
  • 2
  • 12
  • 22
1

After spending almost an hour messing with the URI, changing permissions and configurations and whatnot, I found out I was getting this error message because of a VPN connection I had active. After shutting down the VPN I was able to connect.

So if nothing else works for you, there might be something in your system preventing a connection to be successfully established and mongodb is just responding with bad auth

1

I had this same challenge but I discovered that making my IP address set to my current IP prevented me from accessing the services. Making the database accessible from anywhere was appropriate to access the database either using mongo shell or mongo compass.

Torch
  • 51
  • 1
  • 9
0

The same problem i faced with mongoDB password authentication failed.

"Error: bad auth Authentication failed."

As per Pawan's suggestion given above i replaced my login password in MONGO_URI link with database password and it works. be sure to check that one also.

If you not generated the generate new one or if created earlier then replace with new one.

akshay_sushir
  • 1,483
  • 11
  • 9
0

In my case, my password was wrong, to diagnostic the error, I have been follow the next steps:

I have to try connection by command line: enter image description here

Whit this command: mongo "mongodb+srv://cluster0-j8ods.mongodb.net/test" --username :

enter image description here

The response was again: 2020-04-26T11:48:27.641-0500 E QUERY [js] Error: bad auth Authentication failed. :

then I'm change the password for my user, in my case, root user. and thats it, I'm authorized

EdwinCab
  • 361
  • 1
  • 3
  • 17
  • Yes, so within my application was getting an authentication error (using a DB_URL property in my ```.ev``` file, but when checked via mongosh I was going though fine. It simply turned out to be a mistake in the password specified in the properties file. I think that checking via mongo shell is the first step to do, to make sure that the error is not a trivial one like in my case. – panza Jan 12 '22 at 09:46
0
mongodb+srv://jehat123:<password>@jehatarmancdeniz-x2yf7.mongodb.net/question-answer?retryWrites=true&w=majority

Delete all of password part

Use like this:

mongodb+srv://jehat123:yourpass@jehatarmancdeniz-x2yf7.mongodb.net/question-answer?retryWrites=true&w=majority
armancj2
  • 108
  • 1
  • 4
0

You can also get rid of this error by creating a new database user by going to Database Access from the left side and then go to Add New Database User from right right. Now create a new username and password, click OK. Now replace this new username and password into the MongoUri.

spetsnaz
  • 321
  • 4
  • 6
0

In My case the above error got resolved by setting password variable directly.

DATABASE = "test"
#PASSWORD = os.environ.get("YOUR_PASSWORD") #This line was causing an error in code
PASSWORD = "YOUR_PASSWORD"                  # I added directly password variable

client = connect(
    DATABASE,
    host=f"mongodb+srv://mano:{PASSWORD}@cluster0.e2arj.mongodb.net/?retryWrites=true&w=majority",
    alias="default",
)
0

Changing password worked for me

nB: Not the atlas password

Mohammed
  • 838
  • 6
  • 14
0

mongodb+srv://david:password@cluster0-re3gq.mongodb.net/test?retryWrites=true

  • Replace 'password' with the password you registered for the username specified.
  • Replace 'test' after net with the name of the db you created in collections.
bguiz
  • 27,371
  • 47
  • 154
  • 243
Brendan Gaturu
  • 75
  • 1
  • 3
  • 7
0

For me it turned out to be, that I had to tab out of the password field on the MongoDB Atlas page. Before clicking "Update User"

Paul Smith
  • 166
  • 3
  • 13
0

enter image description here

Just go to the "MongoDB Users tab" where you will find the user list. Click on edit where you can reset the password. Sometimes resetting the password can resolve the issue.

0

if you having this issue and learning mongo by official mongo trainings use m001-mongodb-basics as password for your db. And the correct db name is Sandbox (if you followed all steps)

kyxap
  • 516
  • 6
  • 20
0

This happened to me recently, I found out if you have updated your Mongo Db Password recently, your older databases will still be using the old password.

You can get around this by adding a new user to your Mongo db account or just use the old password.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 24 '22 at 17:38
0
  1. Go to Database on the left hand side
  2. click on browse collection
  3. click on Add My Own Data
  4. provide database name and collection name
  5. Again click on database
  6. click on connect ,connect your application
  7. Select node.js
  8. copy the connection string and keep it in your server.js 9)click on database access , edit password, autogenerate password
  9. Copy the password with mouse , click update user
  10. replace in the url string with this password and you are done
0
First, check your password(regenerate)

if not solved.

please check your MongoDB connect URL MongoDB connect URL

this piece of code is unique,

mongodb+srv://reduxJobBox:<password>@cluster0.b08r8ak.mongodb.net/?retryWrites=true&w=majority

Al Mamun Khan
  • 551
  • 6
  • 7
0

In my case i was entering wrong password, i forgot the password which i entered while creating the user at MongoDB, Entering correct password worked for me.

Wasib Hussain
  • 166
  • 1
  • 8
0

I struggled with this problem for a few hours, until I found out it was my proxy breaker. I turned off the proxy and the project worked fine. The software I used is protonVPN

0
  • Make auto generate password and copy that in place of '' in the link.
  • Make IP Access to 0.0.0.0/0 and retry
  • Don't give "1234567" or any such weak passwords, always auto generate to avoid this issue.