I'm trying to connect to a MongoLab database but keep getting the following error on connection:
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
The code I'm using to connect is:
var mongoose = require("mongoose");
mongoose.connect("mongodb://username:password#ds061474.mongolab.com:61474/apitest");
mongoose.connection.on('error', function (err) {
console.log(err);
});
When I connect using the shell, I have no problems whatsoever. What am I doing wrong?
I have encountered similar problem when connecting the mongo db using mongoose. After exploring a while I found mongoLab is using SCRAM-SHA-1 authentication.
Refer to the question below I tried to upgrade my mongoose to V4.1.11, and then it works for me
Authentication in mongoose using SCRAM-SHA-1
I faced the same issue while I try to import data from the locale to server.
Those 2 parameters can be important, it worked after I put them:
--authenticationMechanism 'MONGODB-CR'
--authenticationDatabase "admin"
Be careful about the auth mechanism, can be a different one. Check this part of documentation: https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption-mongoimport-authenticationmechanism
Had this error myself, turns out I did two things incorrectly (thanks Idos):
Used the mongolab.com username instead of the database one.
Tried to connect to a mongo 3.4 database using a 2.6 shell provided through Ubuntu's repositories. mongo --version to check.
Follow the instructions from this MongoDB page to add their keys and repositories to your APT sources in order to upgrade and keep your MongoDB installation updated going forward.
i had a similar error in that case. put authSourse=admin and ssl=true to your connection
e.g
mongodb://username:password#ds061474.mongolab.com:61474/apitest?authSourse=admin&ssl=true
Related
First of all, I can't find any answers here and Google. I may search the wrong direction and appreciate any help.
Node: 10.24.1/12.22.1/14.17.0/16.3.0 (These are the versions I tried)
Mysql for node: 2.18.1
Knex: 0.95.0/0.95.4/0.95.5 (Versions I tried)
Test environments: two computers (mac & win) in two networks (totally separated)
Background
The code needs to access the mysql database locally. This database has been tested through HeidiSQL(win) and Sequel Ace(mac) on those two computers with the same credentials remotely and successfully.
To avoid interference by other codes, I initiated a new project using npm init. It has one file: app.js and the code is below:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '123.123.123.123', // Remote database IP
user : 'user_name',
password : 'pass',
database : 'mydb'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
200.200.200.200 here is an example of the network's real IP
And the error is below:
code: 'ER_ACCESS_DENIED_ERROR',
sqlMessage: "Access denied for user 'user_name'#'200.200.200.200' (using password: YES)",
sqlState: '28000',
fatal: true
I then clone this mini test project to another computer and tested in a different network with example IP 202.202.202.202 and the error is below:
code: 'ER_ACCESS_DENIED_ERROR',
sqlMessage: "Access denied for user 'user_name'#'202.202.202.202' (using password: YES)",
sqlState: '28000',
fatal: true
Apparently the username has been adapted by the mysql library but the host is not. I assume that the password is taken in as well. because of the using password: YES.
I don't think this is related to the database because without using the correct IP, the code hasn't even touched the database server yet.
It looks like it's using localhost but shouldn't it be 192.168.x.x and I don't use localhost anywhere.
I tried a few versions of node and looks like it's not related to node. knex and mysql are freshly installed using npm. Project is as clean as possible. I can't anywhere that has any problems could cause this.
Any help is appreciated.
Check your database username and password. If it's working before then it should work now and I don't think it's related to node of any of your dependancies.
If it's never working, then try to change your password and try again. From your example the config is used by the mysql lib so there's no reason it picks your username and password but explicitly ignores your host.
This is my mongoose connection code:
mongoose.connect("mongodb+srv://Sarthak:*******:Wb#cluster0-jli2a.mongodb.net/test?retryWrites=true",{ useNewUrlParser: true })
.then(()=>{
console.log("Connected to mongo database");
})
.catch((err)=>{
console.log("Error connecting mongo database",err);
});
I got the errors below, any idea how to fix this?
Error connecting mongo database { MongoParseError: Unescaped colon in authority section
at parseConnectionString (/home/sarthak/Projects/thePracticalGuide/node_modules/mongodb-core/lib/uri_parser.js:250:23)
at QueryReqWrap.dns.resolveTxt [as callback] (/home/sarthak/Projects/thePracticalGuide/node_modules/mongodb-core/lib/uri_parser.js:126:7)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:240:10)
name: 'MongoParseError',
[Symbol(mongoErrorContextSymbol)]: {} }
Just go to atlas website security tab and edit the password of the user and make sure you do not use "#" or ":". That's it.
You need to encode your password in the connection string:
const connectionString = `mongodb://yourUsername:${encodeURIComponent('yourPassword')}#127.0.0.1:27017/mydb`;
Try to use this way of connection too
/* I've removed the ":Wb" between your password and #clus... As mongoDB atlas website didn't use that in my generated connection string */
mongoose.connect("mongodb+srv://Sarthak:*******#cluster0-jli2a.mongodb.net/test?retryWrites=true",{ useNewUrlParser: true });
mongoose.connection.on('error', (err) => {
console.error(`Mongoose connection error: ${err}`);
process.exit(1);
});
Otherwise things to consider:
Make sure that you've added your connecting device IP address in the IP whitelist in the security tap of your cluster in mongoDB atlas website (if you've already done that you might try giving permission to every IPs by adding 0.0.0.0/0 to check there's no issue regarding to this)
Regarding to the password, you may got confused with the mongoDB atlas login password, than the user you made for the cluster (this is a common mistake that mongoDB atlas newbies make).
If not and you're using the right password, you can try to delete the user and re-create it again in the security tab (in the clusters view in mongoDB atlas website). First consider giving the user a very basic password without any special character and try connecting again to ensure that it's not an encoding issue.
At the end if none of above worked with you try making connection via shell. (you can see the connection string in the mongoDB atlas website, in the connect section of your cluster. There you can get better logs regarding to the cause of your problem.
The error description is pretty clear - do you have a colon in your password? The typical connectionstring format is "mongodb+srv:[username:password#]host1..." so an unescaped colon would throw a parse error.
I had this same problem, also with "unescaped colons" even though they were very clearly escaped. Try this:
var uri = encodeURI('mongodb+srv://Sarthak:*******:Wb#cluster0-jli2a.mongodb.net/test?retryWrites=true');
I was getting "Unescaped colon in authority section" using MongoDB Compass when entering the connection string.
For which -
I went into "Create Free Cluster" button and made a cluster.
Then I got the connection string. However, while entering the available connection string I got the error.
I just changed the password by logging into mongodb atlas.
Here is the procedure I used -->
[1] To change the password - click on encode URI
[2] It will take you here -->
[3] Click on the edit button from the screen above and change your password.
I followed the above steps and was able to login.
I have a new sandbox cluster on MongoDB Atlas that I am connecting to with mongoose on a Node.js server. This is the code I'm using to connect:
const mongoDbUrl =
`mongodb+srv://${username}:${password}#mydb-sandbox-12345.mongodb.net/testdb`
mongoose.connect(mongoDbUrl)
const connection = mongoose.connection
connection.on('connected', () => {
console.log('Connected to mongodb')
})
In the Atlas dashboard I have a readWriteAnyDatabase user that I am authenticating with. Authentication works as expected. I am able to connect to the database and no error is thrown on the connection. I can confirm this by removing a character in the password - authentication fails and I'm unable to connect.
The problem is when I try to insert documents.
const UserModel = require('./models/User')
UserModel.create({
name: 'Hello Atlas'
})
I get the following error:
MongoError: not authorized on admin to execute command {
insert: "users",
documents: [
[{
name Hello Atlas
} {
_id ObjectIdHex("5aa17933d72d25730a340611")
} {
__v 0
}]
],
ordered: false
}
As far as I know the user I'm authenticating with should have permission to read and write on the database I'm connecting to. The other part I don't understand is that the error shows that it's trying to write to admin even though my url is connecting to testdb.
Not sure if you have seen this post, but it could be because you are on a free cluster? Hope this helps.
UPDATE
I looked into the problem further and reproduced it on my own. I got the same error. However, I noticed that at one point Atlas provided me with a choice of connection strings. I went back to that page and chose I am using driver 3.4 or earlier.
The connection string looks like this:
const mongoDbUrl = `mongodb://${username}:${password}#cluster0-shard-00-00-1wntz.mongodb.net:27017,cluster0-shard-00-01-1wntz.mongodb.net:27017,cluster0-shard-00-02-1wntz.mongodb.net:27017/testdb?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin`;
It worked with that connection string.
It looks like the free version of MongoDB Atlas launches with v3.4
If you are using free cluster. change 'admin' to 'test' in the path:
mongodb+srv://username:password#cluster0-yauj8.mongodb.net/test?retryWrites=true&w=majority
This worked for me
Going off #rithesh-mys 's answer. Replacing it with "test" is specifying the db. So you have to change it to the db name that you would use.
I had the same problem. I was trying a lot of connection strings, but the one for olders mongo shell (3.4 or earlier) worked for me.
mongodb://my_username:my_password#cluster0-shard-00-00.osobw.mongodb.net:27017,cluster0-shard-00-01.osobw.mongodb.net:27017,cluster0-shard-00-02.osobw.mongodb.net:27017/my_database?ssl=true&replicaSet=atlas-xw3rfy-shard-0&authSource=admin
I think that newer versions of connection strings don't work with mongoose, at least with free clusters.
Make sure the user you have created has the write and read privileges.
I am trying to connect to my AWS Bitnami MEAN instance. The code has been uploaded on the server. But on connecting to it, I am getting the following error :
I have been following the steps given at : https://scotch.io/tutorials/deploying-a-mean-app-to-amazon-ec2-part-1 to connect to the instance.
In the second aprt of it, where they are making changes for mongoDB, I did all those, but since then, I am getting this error.
Your connection is being refused, it seems like an authentication error. You must provide the password in your application, i.e. if you are using Mongoose in order to connect:
var Mongoose = require('mongoose');
var db = Mongoose.createConnection('mongodb://*USER:PASSWORD*#localhost/*DATABASE*');
You must use your correct mongodb socket and your correct password and database name.
Best regards,
Silvio Fernández
I can't connect to a database with mongodb or mongoose on nodejs on my arduino yun.
Unable to connect to the mongoDB server. Error: { [MongoError: Authentication failed.]
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
code: 18,
errmsg: 'Authentication failed.' }
I get that error. The code works fine on my desktop computer.
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://*******:********#address:23118/arduino';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
// do some work here with the database.
//Close connection
db.close();
}
});
I am trying to connect to a mongo lab database. I have not tried connecting to any other database to troubleshoot. This is because I cannot find a free trial version where I do not need a credit card.
EDIT:
I got an Object Rocket instance and it works perfectly on my arduino yun. However it is very expensive; $30 a month (currently on the trial). And I don't need speed or lots of data. So if anyone could figure out why it doesnt work on mlab that would be great.
I've experienced some authentication issues in the past and I've addressed them following the next steps:
1) Identify version numbers of both mongo server and mongoose
2) Identify what authentication mechanism does your server use and make sure that mongoose is trying to authenticate with the one your server is expecting. If you're using an old version, some authentication mechanism might not be supported, so you'd need to upgrade.
3) Identify where the user has been created. Check out Authentication Database and make sure that your client is authenticating using such database. It can be different than the database you store your data. Indeed, it uses to be admin. If so, take a look to the authSource option you can add to your connection string. More info here.
In addition to all of the above, I'd recommend you to use the the mongo client to verify your credentials are right and you can connect to the database.