Cannot read/write on a MongoDB Atlas database using Mongoose - node.js

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.

Related

connecting mongoose to mongoDB atlas and nodejs

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.

Fail to connect Mongoose to Atlas

I'm always connecting to the "admin" DB, which is a fixed bug.
Using Mongoose 5.0.6 MongoDb 3.6 and trying to connect to Atlas.
My question, what driver Mongoose 5.0.6 depend on?
How can I find out when Mongoose will have that fix?
On a different direction, is there a way to connect with MongoDB then use this connection with
Mongoose?
Cheers
Basically you should try connecting with your url link, and specify the DB name on the mongoose connect method
so if your cluster link is:
mongodb+srv://userName:Passwrod#clustor.mongodb.net/
and your DB name is:
testDB
then you should call the mongoose.connect method as follows:
mongoose.connect('mongodb+srv://userName:Passwrod#cluster.mongodb.net/', {dbName: 'testDB'});
Connection is established when you use this connection string for (MongoShell 3.6+) :
var connDB = "mongodb+srv://<username>:<password>#cluster-fax0w.mongodb.net/test"
However, you will not be able to read/write data without entering the DBName in the mongoose.connect().
mongoose.connect(uri, { dbName: <your DB name> })
.then( () => {
console.log('Connection to the Atlas Cluster is successful!')
})
.catch( (err) => console.error(err));
Just a side note if you ever get an error connecting to the MongoDB Atlas make sure:
You've whitlisted our IP address / all (0.0.0.0/0)
Your credentials are right
Firewall / anti-virus are disabled
And if all fails
Make sure your DNS is a public one. Or maybe change it to Google's public DNS.
Throwing a link for the same:
https://www.youtube.com/watch?v=F9u5ULrRt3Y
Goodluck!

How do I correctly authenticate in mongo for a user that has access to multiple databases?

I have a user with the role: {role: 'root', db:'admin'} which should have access to all the databases in my mongo instance. I'm using mongoskin in node.js to interact with mongo. My problem is that it isn't correctly accessing my databases. If I authenticate with
mongodb://owner:mylocalpassword#localhost:27017/mydatabase
It simply gives me MongoError: Authentication failed. If I instead auth with:
mongodb://owner:mylocalpassword#localhost:27017/admin
it authenticates, but I can't access mydatabase.
Here's my connection code:
var connection = mongoskin.db("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal:true, auto_reconnect:true})
I assume that since I'm accessing the admin database there, that's the only one it interacts with. So I tried do then do this:
var mydatabaseConnection = connection.db('mydatabase')
But when I use that, my app is returning no results for queries on collections that I know have data. What am I doing wrong here? How do I get this user to access a database other than admin?
Ok, so I found out that mongoskin's db method simply doesn't work. Finally I'm forced to completely remove mongoskin from my codebase. The real answer here is don't use mongoskin.
This code worked with mongo native:
MongoClient.connect("mongodb://owner:mylocalpassword#localhost:27017/admin", {journal: true, auto_reconnect:true}).then(function(db) {
console.log("Connected!")
var mydb = db.db('mydatabase')
var User = mydb.collection('User')
return User.find({}).toArray().then(function(users) {
console.log(users)
db.close()
})
}).catch(function(e) {
console.log(e.stack)
})

Bitnami Meanstack Mongoose Connection

I created a simple service in Ubuntu 16.04 with mongo db node and express to return data to an angular 2 app.
I have a file called server.js that connects to a local mongodb instance with a database called game and a collection called players. It works fine installed on my local machine. However I am trying to deploy it with Bitnami's mean stack image on amazon ec2. (bleh mouth full). I have set ports correctly according to this guide, and I can connect to it remotely. However, I can't get mongoose to connect to any database. here is my code that works on my local machine.
mongoose.connect('mongodb://localhost:27017/game');
router.route('/player')
.get(function(req, res) {
console.log(mongoose.connection.readyState);
Player.find({"player":user,"password":password},function(err, Test) {
if (err)
res.send(err);
res.json(Test);
});
});
And here is my adjusted code for the mean stack image
mongoose.connect('mongodb://root:"My-Root-Password#127.0.0.1:27017/game');
router.route('/player')
.get(function(req, res) {
console.log(mongoose.connection.readyState);
Player.find({"player":user,"password":password},function(err, Test) {
if (err)
res.send(err);
res.json(Test);
});
});
On my local machine I get a value of 1 on the console.log and value of zero on the mean stack image. I'm not sure how to connect to bitnami's mongo instance with mongoose. I have checked that game exist and has the data I want.
I found a fix Although I don't yet fully understand it. It came from the guide I posted here . First I had to un comment out the section of the mongodb.conf that says noauth = true then comment out the line that says auth = true. I then restart mongo, and create a new user with permissions to read and write the the data base I want to use like this
db.createUser({
user: "NEW USERNAME",
pwd: "NEW PASSWORD",
roles:[
{
"role" : "readWrite",
"db": "game"
}
]})
After creating the user I undo what I did to noauth = true and auth = true, and restart mongodb. Then I am able to connect with mongoose like this
mongoose.connect('mongodb://NEW USERNAME:NEW PASSWORD#127.0.0.1:27017/game');
With MongoDB 3.0, they added a new authentication mechanism for MongoDB (more details in the links below).
Authentication information: https://docs.mongodb.com/manual/core/authentication/
How to use the new authentication mechanism: https://www.mongodb.com/blog/post/improved-password-based-authentication-mongodb-30-scram-explained-part-2
Due to this, the guide provides that workaround to get the connection with the database. Now, you have created that user with "readWrite" privileges on your database so you are able to use it.

Auth failed, code 18 when connecting to MongoLab database

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

Resources