Can't connect Mongoose to MongoDB with authentication - node.js

I created a user with readwrite role for MongoDB database myDatabase.
After starting MongoDB server with --auth, in Mongo shell:
mongo -u userName -p userPassword --authenticationDatabase myDatabase
Connects properly and can read/write myDatabase
In mongoose tried to connect to MongoDB using
mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword'});
Also
mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword', {auth: {authdb:'myDatabase'}});
Able to connect to myDatabase but get authorization error when read/write
MongoError: not authorized for query on myDatabase.myCollection
How can I fix this?

I would suggest to try the following:
1) Connect with string URI format https://docs.mongodb.org/manual/reference/connection-string/
2) Which version of mongoose are you using? According to the docs http://mongoosejs.com/docs/connections.html you should provide 'pass' property but you are passing it as 'password'.

You should specify the auth database. Your second attempt was almost correct but instead of authdb you should use authSource options. In your case it should be
mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword', {auth: {authSource:'myDatabase'}});

Related

Mongoose times out if databasename is set

I'm rather new to Linux, NodeJs and MongoDB but I setup a Linux Server running a MongoDB (db version v4.0.16).
I added two users like this. One called mongo-admin and one called mongo-root.
# mongo
> use admin
> db.createUser({
user: "mongo-admin",
pwd: "myAwesomePassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
> db.createUser({
user: "mongo-root",
pwd: "myAwesomePassword",
roles: [ { role: "root", db: "admin" } ]
})
I then enabled authentication in /etc/mongod.conf like this
security:
authorization: "enabled"
On my development Machine I setup a little NodeJS script that tries to connect to the server using mongoose, and simply add a document there.
Now the situation is very strange. If I use mongodb://mongo-root:myAwesomePassword#100.100.100.100:27017 as a connectionstring, everything works fine and a new DB named test is created and the document is added. But as soon as I add a /mydatabasename at the end of the string, mongoose will suddntly time out after 30 seconds of trying to connect.
If I connect to MongoDB using a Software called Robo3T, I can connect just fine, and I also have the rights to create a new database just fine.
I also checked the /etc/log/mongod.log and found this error:
2020-02-05T07:40:22.006+0000 I ACCESS [conn27] SASL SCRAM-SHA-1 authentication failed for mongo-root on mydatabasename from client 101.101.101.101:51270 ; UserNotFound: Could not find user mongo-admin#mydatabasename
This is the way I connect to the DB
mongoose.connect(
"mongodb://mongo-root:myAwesomePassword#100.100.100.100:27017/mydatabasename",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
);
It seems like mongodb is looking for the user in the database that should be created instead of in the admin db.
Check Connection String URI Format
mongodb://[username:password#]host1[:port1][,...hostN[:portN]][/[database][?options]]
/database
Optional. The name of the database to authenticate if the connection
string includes authentication credentials in the form of
username:password#. If /database is not specified and the connection
string includes credentials, the driver will authenticate to the admin
database. See also authSource.
authSource
Specify the database name associated with the user’s credentials.
authSource defaults to the database specified in the connection
string.
Actually the documentation is not 100% correct for this point, the connection string must be like this:
mongodb://mongo-root:myAwesomePassword#100.100.100.100:27017/mydatabasename?authSource=admin

Cannot read/write on a MongoDB Atlas database using Mongoose

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.

How to operate the databases in MongoDB in nodejs via mongoose?

The MongoDB has set the property 'auth' with true, in commond line, you must log in Admin first, and then you can operate other databases.
In nodejs, I wrote the connection like this:
mongoose.connect('mongodb://username:pwd#127.0.0.1 :27017/test');
But it' s failed, do I need to connect Admin first, if so, how?

How to connect to monogodb using monk?

I am building a nodejs app using expressjs framework. I would like to ask how do we connect to mongodb using monk? i found this code online however it seems that we do not need to specify username and password. why is that so?
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
Appreciate any advice.
There are two methods of passing username/password:
// first:
var db = monk('USERNAME:PASSWORD#localhost:27017/nodetest1');
// second:
var db = monk('localhost:27017/nodetest1', {
username : 'USERNAME',
password : 'PASSWORD'
});
It's not very well documented, but since monk uses mongoskin, you can look here for more information.
I want to add an alternative to the answers above as neither worked for me.
So the way I was able to connect to a mongod --auth instance was:
1.Make sure you create a user while logged into mongodb as a user with appropriate permissions to create users on databases (like a user with the role userAdminAnyDatabase). If you don't have a user with this role restart mongo with just mongod without --auth and login as your superuser (if you have one) or with a simple mongo command and make this user with the appropriate privileges.
I highly recommend reading up on mongodb roles here: http://docs.mongodb.org/manual/reference/built-in-roles/
2.Once you are logged into your database instance with the appropriate user who is supposed to be creating other users, type use db_name where db_name is the name of your database that you want to make the user for.
3.Once inside this database use the db.createUser command like so: db.createUser({user:"your_username", pwd:"your_password", roles:["your_role"]})
It's documented here: http://docs.mongodb.org/manual/reference/method/db.createUser/
4.Then just use db = monk('USERNAME:PASSWORD#localhost:27017/DATABASE_NAME') in your code.
After you've done this you should be able to log into a running mongod --auth instance with a user for the particular database you created that user for.
For anyone curious I'm developing a little web app in Koa. Using monk and co-monk.
In apps.js:
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/ta');
module.exports = db;
In /lib/mylib.js:
var db = require('../apps.js')
Though i would recommend making a separate file called db.js and in that file export the connection ,that is more cleaner.

In nodejs with MySQL

I am Using Nodejs with MySQL.
But problem is that My MYSQL Connection Password Able to see in browser, With this any user get my my SQL username and Password.
Is it possible no one can see my MySQL Connection permanent as its is a server side.
Can any one help me in this.
Do not send you password to client but store it in a variable inside your server-side script. On a request, use it to access database and send only the result of the operation.
If you show your code you might get a more detailed answer then this...
var connection = mysql.createConnection({
host : 'host',
user : 'dbuser',
password : "pword",
database : 'database',
});
connection.connect();
connection.query(etc etc etc)
for full example see mysql module in node.js not works in my case
or another way is to save the configuration and password details in either an env file or other file (or even sqlite db file and load it on startup/restart of your script

Resources