how to authenticate mongoose connection mongodb in node.js - node.js

I have created mongodb user with command
use admin
db.createUser(
{
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
}
)
then in my app I am trying to connect mongoose like this
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';
mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
I am getting this error when inserting data through mongoose
MongoError: not authorized for insert on twitter-mongo.users
please tell me what is wrong in my code

You must declare the authSource parameter in your connection string in order to specify the name of the database that contains your user's credentials:
var options = {
user: "superuser",
pass: "12345678"
};
var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';
Note: for users of Mongoose 4.x, you may want to also include useMongoClient: true in your options object. This silences the Please authenticate using MongoClient.connect with auth credentials and open() is deprecated error messages.

This is working fine:
var options = { server: { socketOptions: { keepAlive: 1 } } };
var connectionString = 'mongodb://admin:admin1234#localhost:27017/myDB';
mongoose.connect(connectionString, options);
//Add those events to get more info about mongoose connection:
// Connected handler
mongoose.connection.on('connected', function (err) {
console.log("Connected to DB using chain: " + connectionString);
});
// Error handler
mongoose.connection.on('error', function (err) {
console.log(err);
});
// Reconnect when closed
mongoose.connection.on('disconnected', function () {
self.connectToDatabase();
});

try this
const mongooseConnectionString = 'mongodb://superuser:12345678# localhost/twitter-mongo?authSource=admin'

I did run a mongo service using docker and then connected my mongoose to it with this code
const _database = 'mongodb://user:pass#localhost:port/MyDB?authSource=admin';
mongoose.connect(_database, {
useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB ...'))
.catch(err => console.error('Could not connect to MongoDB:‌', err));
this is equal to
mongo --username user --password pass --authenticationDatabase admin --port 27017
on connection and then use MyDB database for doing operations like find, aggregate, insert and etc on it.
if you have no user (MongoDB default user) for your database then you can change Database like bellow:
const _database = 'mongodb://localhost:port/MyDB';
27017 is default MongoDB port if your MongoDB port hasn't changed either then you can do the same for port too.
like bellow:
const _database = 'mongodb://localhost/MyDB';
this is the same as bellow:
mongo
above code is because there is no user and no port then for not been a user there is no need for authentication database either.

mongoose.createConnection('mongodb://username:password#35.238.xxx.xxx:27017/dashboards?authSource=admin', {
useNewUrlParser: true
}, (e) => {
if (e) throw console.error('Error connecting to mongo database master');
console.log('Connected to mongo database master.');
});

You need to create an User in database which you are operating on, not the admin DB.
Use this command,
use twitter-mongo;
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});
Instead of this,
use twitter-mongo
db.createUser({
user: "superuser",
pwd: "12345678",
roles: [ "root" ]
});

Correct way to create the connection string is
var connection = mongoose.createConnection("mongodb://username:pwd#hostip:port/dbname?authSource=admin", options);
Please use authSource=admin to authenticate in connection string.

Related

Failed to connect SQL Server from Node.js using tedious

I am trying to connect to SQL Server in our domain network. I am able to connect using python but not able to connect in Node.js using Tedious.
Node.js code snippet:
var config = {
server: 'serverName.domain.com',
authentication: {
type: 'default',
options: {
userName: 'DOMAINID\\username',
password: 'password'
}
},
options: {
database: 'dbName',
port: 1234,
}
};
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log('err', err);
} else {
console.log("Connected");
executeStatement();
}
});
connection.connect();
Receiving error:
Login Failed for the user DOMAINID/username. The login is from an untrusted domain and cannot be used with Windows authentication.
But when trying to connect from Python, I am able to connect successfully.
Python snippet:
import sqlalchemy
conn = sqlalchemy.create_engine('mssql+pymssql://DOMAINID\\username:password#serverName.domain.com:1234/dbName')
print(conn.execute('SELECT * FROM table_name').fetchall())
Data received successfully in python.
And also I tried with mssql and msnodesqlv8 with Microsoft ODBC 11 for Microsoft SQL Server drivers.
I am able to connect. Following is the code snippet.
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "server.domain.com",
database: "dbName",
port: 1234,
user:'DomainId\\username', // Working without username and password
password:'password',
options: {
trustedConnection: true // working only with true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = 'select * from table';
const result = await request.query(query);
console.dir(result);
};
main();
In the above snippet, I am able to connect without username and password but with trustedConnection true only. I am using windows authentication not SQL authentication. How can I connect using tedious js

Failed to connect node.js app to MongoDB Atlas despite using the correct connection credentials

I'm trying to connect my node.js application to MongoDB Atlas but I keep getting a "Bad authentication error" and yes, I am using the current database user credentials.
Here is the snippet that's supposed to connect to MongoDB Atlas
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
console.log('MongoDB Connected: ' +conn.Connection.host)
}catch (err) {
console.error(err)
process.exit(1)
}
}
My terminate shows me bad authentication and some key-pairs that look so:
{
ok: 0,
code: 8000,
codeName: 'AtlasError',
name: 'MongoError'
}
Any ideas why it is not connecting to MongoDB Atlas?
I finally singled out the problem, it was the MongoDB connection string. I was simply inserting my password in the password field without removing the angle brackets.

Connection to postgresql db from node js

I'm tyring to make a connection from my nodejs script to my db connection, but seems like there is a suspicius issue i'm not able to figure out.
At the moment, this is my code:
const { Pool } = require('pg');
const pool = new Pool({
user: 'user',
host: '192.168.1.xxx',
database: 'database',
password: 'password',
port: 5432,
});
pool.on('error', (err, client) => {
console.error('Error:', err);
});
const query = `SELECT * FROM users`;
pool.connect()
.then((client) => {
client.query(query)
.then(res => {
for (let row of res.rows) {
console.log(row);
}
})
.catch(err => {
console.error(err);
});
})
.catch(err => {
console.error(err);
});
The issue seems to be in pool.connect(), but i can't understand what i'm missing because i got no errors in the log. I've installed pg module in the directory of my project with npm install --prefix pg and i know modules are loaded correctly.
I edited postgresql.conf:
# - Connection Settings -
listen_addresses = '*'
and pg_hba.conf
host database user 192.168.1.0/24 md5
to make the database reachable via lan and seems liek it works, because i'm able to connect successfully with apps like DBeaver...but i can't with NodeJS.
It's possible there is some kind of configuration i've to active?

Exception handling not working for PG npm package

I installed "pg": "^8.0.2" and created the database.js file with database credentials. But no matter what go wrong it never enters in the catch block to show error. Instead it always logs connected to the database. Can anyone point out what I'm doing wrong. Thank You!
Database.js
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'roothjk',
host: 'localhost',
database: 'sf',
password: 'admin',
port: 5432
});
try {
pool.connect()
console.log('connected to the db');
} catch (e) {
console.log('Error connecting to db');
}
connect returns a Promise, and then you move to the next statement. Instead, you should use the then and cath methods:
pool.connect()
.then(c => console.log('connected to the db'))
.catch(e => console.log('Error connecting to db'));

Getting error while connecting to mongoDB database using Node.js

I am getting the following error while connecting the mongoDB database present in MLAB using Node.js.
Error in DB connection : {
"name": "MongoNetworkError",
"errorLabels": [
"TransientTransactionError"
]
}
Here is my code:
var mongoose = require('mongoose');
const authData = {
"useNewUrlParser": true,
"useCreateIndex": true
};
//connecting local mongodb database named test
mongoose.connect(
'mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd',
{useCreateIndex: true, useNewUrlParser: true,useUnifiedTopology: true },
(err)=>{
if (!err)
console.log('MongoDB connection succeeded.');
else
console.log('Error in DB connection : ' + JSON.stringify(err, undefined, 2));
}
);
module.exports = mongoose;
Here my database is present inside MLAB but when I am tring to connect to that DB its throwing me that error. I need to connect to my database here.
"useCreateIndex": true and useUnifiedTopology: true is deprecated .
Try out the following code to connect your mongoDB database .
mongoose.connect('mongodb://subhra:*****#ds139989.mlab.com:39989/hlloyd', {useNewUrlParser: true})
.then(() => console.log("Connected"))
.catch(err => console.log(err));
module.exports = mongoose;
Please add your current IP or 0.0.0.0 to whiteList following "main page > security section > network access > add IP" in MongoDB website.
I hope this helps.

Resources