Mongoose times out if databasename is set - node.js

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

Related

How to configure apache tomcat server to the oracle database

I have created an application based upon node JS and react JS, here I am using the oracle database for the data with node JS. The issue here is that the application is able to run but it does not able to make any API calls because all the data that needed to be handled is on the oracle database, I think the application does not able to establish a connection to the oracle database server.
I am new to this whole deployment stuff and this my first web based project.
Here is the configuration code for the database connectivity:
module.exports = {
database:{
user : 'user_name',
password : 'pass',
connectString : 'something'
},
jwtSecretKey: "jmvhDlong......."
};
I am using two oracle database server, one for storing the user details and the second to fetch the details:
Code for the user database server:
module.exports = {
database:{
user : 'user_name',
password : 'pass',
connectString : 'something'
},
jwtSecretKey: "jmvhDlong......."
};
Code for the database server from which the details need to be fetched:
module.exports = {
database:{
user : 'user_name',
password : 'pass',
connectString : 'something'
},
};
And don't worry about the user, password and connectstring those are correct.
I need to bypass the apache server configuration so that the application can able to connect to the oracle database and able to make the API calls.
do you want to use appache as a user to login to an oracle-db?
there is a parameter for ms-sql, called integratedSecurity (=true), and you can set a software as a user in db, so you can acces ms-sql with tomcat.
if you want to do something like this, i think this isnt possible, my knowlegde is 2years old, dont know if something changed meanwhile.

Sequelize unable to connect to SQL Server through network

My setup is the following:
I have a Virtual Machine running all of my Database processes, let's call it DB-VM.
I'm currently developing at my own workstation (completely detached from DB-VM, except that we are under the same network.
I've created a valid connection string, validated by another database connection service throughout IIS and through a Data Link Properties file (.udl) and the connection.
This connection is described by the connection string as:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Data Source=DB-VM\MY_DATABASE.
I tried to insert it into my Sequelize configuration as following:
const sequelize = new Sequelize({
dialect: 'mssql',
dialectModulePath: 'sequelize-msnodesqlv8',
dialectOptions: {
connectionString: 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Data Source=DB-VM\MY_DATABASE',
trustedConnection: true,
}
});
And then proceeded to try and authenticate through:
sequelize.authenticate().then(() => {
console.log('Connection stablished successfully!');
}).catch(err => {
console.log(err);
});
And this the error is as follows:
Notice: The database uses dynamic ports, therefore I can't specify the port through the port property.
Notice 2: The Named Pipes are disabled on my database settings, and I'm not sure if I will be able to enabled it.
Notice 3: The database is already setup to allow remote connections (it is currently used through a Webpage and works fine!
According to this line the sequelize-msnodesqlv8 library expects "Driver" to be a part of the connection string, otherwise it tries to guess. Besides that, all the examples of connection strings here1 and here2 are using either Server=myServerName\theInstanceName or just Server=myServerName. Instead of the Data Source=....
So step 1 is to fix you connection string. You could try one of the examples like:
dialectOptions: {
connectionString: 'Driver={SQL Server Native Client 10.0};Server=DB-VM;Database=MY_DATABASE;Trusted_Connection=yes;'
},
After that if you get a new error, please update the question.

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 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)
})

Can't connect Mongoose to MongoDB with authentication

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'}});

Resources