Reputation: 869
I've tried this and it's not working.
I have the following error with Mongodb + Atlas:
MongoError: bad auth Authentication failed.
at /Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/auth/auth_provider.js:46:25
at /Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/auth/scram.js:215:18
at Connection.messageHandler (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connect.js:334:5)
at Connection.emit (events.js:203:13)
at processMessage (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/Users/cyrus/Documents/Code/01. Code/Franklin-ford/franklin-ford-server/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at TLSSocket.emit (events.js:203:13)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:276:11)
at TLSSocket.Readable.push (_stream_readable.js:210:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:166:17) {
ok: 0,
errmsg: 'bad auth Authentication failed.',
code: 8000,
codeName: 'AtlasError',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {}
Here's how I instantiate my DB:
From the credentials.js
:
const config = {
mongoConnectionURL: "mongodb://cyruslk:<MY_PASS_HERE>@franklinford-shard-00-00-3dveb.mongodb.net:27017,franklinford-shard-00-01-3dveb.mongodb.net:27017,franklinford-shard-00-02-3dveb.mongodb.net:27017/test?ssl=true&replicaSet=FranklinFord-shard-0&authSource=admin&retryWrites=true&w=majority",
mongoDatabaseName: "FranklinFord",
}
From my main server.js
app:
const {MongoClient} = require("mongodb");
const connectionURL = config.mongoConnectionURL;
const databaseName = config.mongoDatabaseName;
let sendToDb = (dataToInsert) => {
MongoClient.connect(connectionURL, {
useNewUrlParser: true,
}, (error, client) => {
if(error){
console.log(error);
return console.log("Unable to connect to the db.");
}
const db = client.db(databaseName);
console.log(db);
db.collection("ford_twitter").insertOne({
masterData: dataToInsert
}, (error, result) => {
if(error){
return console.log("unable to insert users");
}
console.log("Data successfully inserted");
})
})
}
You can find the code here
Thanks for helping me. I have no idea what's happening.
Upvotes: 30
Views: 94165
Reputation: 59557
There are two common problems, when your authentication (by password) fails. First one is related to the authentication database. See Authentication failure while trying to save to mongodb
For the second common issue, there are so many answers, but none of them refers to the documentation.
If the username or password includes the following characters, those characters must be converted using percent encoding:
$ : / ? # [ ] @
In Javascript/Node.js you can use encodeURIComponent() function to do that. I think almost every programming language has similar build-in function.
Note, above list of reserved characters contradicts to troubleshooting guideline Special Characters in Connection String Password where it says:
The following characters and the space character must be converted using percent encoding if included in a username or password:
: / ? # [ ] @ ! $ & ' ( ) * , ; = %
Note, in MongoDB you can also authenticate by X.509 certificates, LDAP, Kerberos, AWS IAM credentials or OpenID Connect OIDC. Some of these are only available in MongoDB Atlas or Enterprise edition. There you may face other problems, but I think it would out-of-scope for this question.
Upvotes: 0
Reputation: 456
For me I changed my password and it started working.
Security >> Database Access >> Edit Database User >> Change Password
Upvotes: 0
Reputation: 51
If someone else is searching endlessly and several stack overflow threads checked answer still isn't doing it,.....
If you are using Atlas Authentication Methods: M0 (M0 is the free sandbox), M2, M5, and M10 clusters support only specific authentication methods, such as Password (SCRAM-SHA1), X.509 Certificates, and AWS IAM.
Command Line Tool Options: Some command line tool options, such as --restoreDbUsersAndRoles, --oplogReplay, --preserveUUID for mongorestore, and --dumpDbUsersAndRoles, --oplog for mongodump, are not supported in M0, M2, M5, and M10 clusters.
These limitations are in place to ensure the stability and performance of the shared infrastructure used by M0, M2, M5, and M10 clusters. For more information, you can refer to the MongoDB Atlas documentation on "Unsupported Commands in Atlas" and "Atlas M0 (Free Cluster), M2, and M5 Limits". Related resources:
https://mongodb.com/docs/atlas/unsupported-commands/
https://mongodb.com/docs/atlas/reference/free-shared-limitations/
Upvotes: -1
Reputation: 9
I had same issue too. My problem was that I was using dotenv.config()
after URI which was causing password to be undefined. Problem was solved when I put dotenv.config()
before URL. Be careful about this mistakes.
Upvotes: -1
Reputation: 83
Double check that your IP is 'whitelisted' on your MongoDB Atlas "Network Access" settings, or use the 'access from anywhere' option, which is: 0.0.0.0/0 (includes your current IP address).
I don't know if this will help anyone: for me, I was starting my server via: node app.js
I did npm start instead (my package.json reads: "start": "node server/app.js") and my connection went through.
Perhaps running the server without npm, the .env file was not being recognized, I honestly have no idea but it worked.
Upvotes: -1
Reputation: 449
In my case I was putting the DB_URL inside the doten (.env file), and by mistake I put the DB_URL like this:
DB_URL = "mongodb+srv://USERNAME:<password>@cluster0.8v3jxwm.mongodb.net/?retryWrites=true&w=majority"
And this is a mistake, we do not must add a string quotation here, it must be like this:
DB_URL = mongodb+srv://USERNAME:<password>@cluster0.8v3jxwm.mongodb.net/?retryWrites=true&w=majority
Upvotes: 0
Reputation: 83
The allowed special characters was where I was going wrong. If you enter your password in the connection URL exactly how you entered it in your account and include some of the characters contained here, it will not work.
Upvotes: 0
Reputation: 11
I had the same issue and what worked for me was changing my user's name, from yazi-kun to yazikun I believe that your username should not contain space or any special character
Upvotes: 1
Reputation: 15
check your username and password of your database created NOT from you network.
like this
username password name of ur database
mongodb+srv://eshop1235:[email protected]/eshop-database?retryWrites=true&w=majority
all of these answer u will find in:
right navigation:
security
quickstart
database access
network access
the ooptions edit.
before doing it, please check whether ur databased is "active".
Upvotes: -1
Reputation: 65
I also facing the same issue and I removed +srv and it worked for me.
Upvotes: 4
Reputation: 1
If you are using dotenv then first make sure you have installed it and called it from index.js page
require('dotenv').config();
Then the most uncommon mistake might be Creating a variable named "USERNAME" in the .env file.
//Do not create a variable named USERNAME=abc in the .env file
Upvotes: 0
Reputation: 11
First, the error MongoServerError: bad auth: Authentication failed indicates username and password may be incorrect.
Solution: In credential.js remove the brackets <> around username and password then you have a database connection.
Upvotes: 1
Reputation: 54
This error is not only about the password. Here Database Name, Password and Username do matter.
Since Database name, Password and Username are part of the url, therefore if you use any special character in any of these three part of your url, then you need to replace them with %
and then ASCII Code
of those special sign. For example: for $-
sign you need to replace it with %36%45
And obviously remove <
and >
sign also from the initial link you copied which is like <password>
.
See ASCII Code Here
See the image to understand more
Upvotes: 0
Reputation: 39
Use this
const config = {
mongoConnectionURL: "mongodb://cyruslk:[email protected]:27017,franklinford-shard-00-01-3dveb.mongodb.net:27017,franklinford-shard-00-02-3dveb.mongodb.net:27017/test?ssl=true&replicaSet=FranklinFord-shard-0&authSource=admin&retryWrites=true&w=majority",
mongoDatabaseName: "FranklinFord",
}
NOTE:
remove '<' & '>' from the username and password and make sure that the username and password lies just before and after the colon (symbol = ":" ) there should be no empty space before and after the colon
Upvotes: 1
Reputation: 1
The solution for this is make sure you username and password should include '_' between name and number if in case your name or password includes number
Upvotes: 0
Reputation: 1
I faced the same problem and found the solution. but changed the database password and it works. [try to keep the auto-generated password]
Upvotes: -2
Reputation: 9
making a new admin user account worked for me. i found this was not only case with pymongo but also when I was working with mongo shell.
Upvotes: 0
Reputation: 7
pip install djongo
pip install dnspython
DATABASES = {
'default': {
'ENGINE': 'djongo',
"NAME": "database name",
"CLIENT": {
"host": "connection_string_to_mongodb",
},
}
}
the above code worked for me. separately providing username and password didn't work
Upvotes: -3
Reputation: 348
I faced the same problem I have changed the password but it didn't work. My Password includes numbers I removed them and it worked
Upvotes: 13
Reputation: 1059
Might as well try to add your IP to the white list. Go to Network Access -> Add IP Adress -> Current IP, then save changes and try again, hope it'll help.
Upvotes: -1
Reputation: 2268
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 :)
Good luck!
Upvotes: 60
Reputation: 581
Also try it as,
'CLIENT' : { 'host' : 'connection_string_to_mongodb' }
since, connection_string has username, password, database name, clustername and so, just have this one key-value pair in the client. It worked for me.
Upvotes: 0
Reputation: 516
I had same problem, in that connection string it was written "mongodb+srv://<username>:<password>@cluster0.4h226.mongodb.n..."
and you are supposed to enter username and password in that string.
suppose my username is "user" and password is password, we are supposed to write "mongodb+srv://user:[email protected]..."
, without "<" and ">";
If there are any special characters in your password, replace them with their ascii code preceded by the %
sign. For example, #
would be %35
.
Upvotes: 50