Mongolab connection not working properly - node.js

I have a simple NodeJS service which uses mongodb. The thing is now I am "migrating" to mongolab insted of a local mongodb. The connection is working properly but when my service trys to retrieve some data, the following error apears:
{ [MongoError: auth failed]
name: 'MongoError',
message: 'auth failed',
ok: 0,
errmsg: 'auth failed',
code: 18 }
I've check some similar problems which and discarded the following isues:
Is not the mongolab URL.
Is not the mongolab database user (I am using admin/admin which has dbOwner role).
Server connection:
var db = mongojs('mongodb://admin:admin#xxxxx.mongolab.com:xxxxx/database', ['players']);
Service
app.get('/player', function (req, res) {
db.players.find().sort({_id:-1},function(err,docs) {
if (err) {
console.log(err);
}
res.json(docs);
});
});

Related

Error connecting NodeJS and SQL Server - Could not connect (sequence)

I'm trying to create a connection with SQL Server and NodeJS as shown below (SQL Server installed locally -> localhost):
It's throwing the following error: ERROR: Failed to connect to MY_SERVER:1433 - Could not connect (sequence)
This didn't work either.
I thought it was a problem with the SQL Server installation, but via Python It works well on the same database.
I'm using SQL Server 2019 and latest NodeJS version.
REFERENCE:
https://learn.microsoft.com/en-us/sql/connect/node-js/step-3-proof-of-concept-connecting-to-sql-using-node-js?view=sql-server-ver15
How to fix this error?
var config = {
server: 'MY_SERVER',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'admin'
}
},
options: {
encrypt: false, // I've already tried with "true" also.
database: 'MyDataBase'
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log("Error: ", err.message);
} else {
console.log("Connected");
}
});
connection.connect();
I got it!! Basically, for NodeJS get connection to SQLServer, the TCP/IP Protocol must be enabled for the MSSQLSERVER Instance, in the SQL Server network settings.
Ref.:
Nodejs connection with mssql showing error
https://store.oceansystems.com/knowledgebase/quickdme-faqs/sql-server-sql-express/configure-sql-express-server-host-enable-tcp-ip-firewall-settings/

Unable to connect remote db2 with node js

I am trying to connect remote ibm db2 with node js in mac machine but I'm getting following error
[Error: [IBM][CLI Driver] SQL1598N An attempt to connect to the database server failed because of a licensing problem. SQLSTATE=42968
] {
error: '[node-ibm_db] SQL_ERROR',
sqlcode: -1598,
message: '[IBM][CLI Driver] SQL1598N An attempt to connect to the database server failed because of a licensing problem. SQLSTATE=42968\n',
state: '42968'
}
And this is how I'm trying to connect
function db2Connection() {
var ibmdb = require('ibm_db');
var connStr = "DATABASE=dbname;HOSTNAME=mydb.ibm.com;UID=userid;PWD=password;PORT=447;PROTOCOL=TCPIP";
ibmdb.open(connStr, function (err,conn) {
if (err) return console.log(err);
conn.query('SELECT * FROM T_Name FETCH FIRST 6 ROWS ONLY', function (err, data) {
if (err) console.log(err);
else console.log(data);
conn.close(function () {
console.log('done');
});
});
});
}
db2Connection();
I went through some docs regarding that error but did not get any solution. Can anyone help on how to achieve this.

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.

Expressjs Not Returning All Properties From msnodesqlv8 err Object

In the code below, I'm causing an error (for illustration) by attempting to connect to a database that doesn't exist on the SQL Server.
const sql = require("msnodesqlv8");
const express = require("express");
const app = express();
// Start server and listen on http://localhost:8081/
const server = app.listen(8081, function () {
console.log("Server listening on port: %s", server.address().port)
});
const connectionString = "Server=.;Database=DatabaseThatDoesNotExist;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
const sql = "SELECT * FROM dbo.Table1";
app.get('/', function (req, res)
{
sql.query(connectionString, sql, (err, recordset) => {
if(err)
{
console.log(err);
res.status(500).send(err);
return;
}
// else
res.json(recordset);
});
})
The result of console.log(err); lists the error objects with four properties (code, message, sqlstate and stack):
Array(2) [Error: [Microsoft][SQL Server Native Client 11.0][…, Error: [Microsoft][SQL Server Native Client 11.0][…]
codefile.js:33
length:2
__proto__:Array(0) [, …]
0:Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'.
code:18456
message:"[Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'."
sqlstate:"28000"
stack:"Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'."
__proto__:Object {constructor: , name: "Error", message: "", …}
1:Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed.
code:4060
message:"[Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed."
sqlstate:"42000"
stack:"Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed."
__proto__:Object {constructor: , name: "Error", message: "", …}
However, the result of res.status(500).send(err); (seen in the client) only contains two properties (sqlstate and code):
[
{
"sqlstate": "28000",
"code": 18456
},
{
"sqlstate": "42000",
"code": 4060
}
]
How do I get express to return the message and stack properties also?
The problem is that Error does not have enumerable fields and therefore message and stack don't get serialized to JSON.
See this question for ways to serialize the error object.
A quick solution for your case: res.status(500).send({message: err.message, stack: err.stack});
But this is of course not scalable. A better approach would be to configure the json replacer for express:
app.set('json replacer', replaceErrors);
And use the replacer implementation from the linked question excellent answer by #jonathan-lonowski:
function replaceErrors(key, value) {
if (value instanceof Error) {
var error = {};
Object.getOwnPropertyNames(value).forEach(function (key) {
error[key] = value[key];
});
return error;
}
return value;
}

Node.js MongoError: auth failed

I found out my website wasn't working anymore because i can't auth to my mongolab DB.
here is my code (it used to work for months):
var mongoose = require('mongoose');
mongoose.connect('mongodb://USER:PASSWORD#ds053419.mongolab.com:53419/jobinfest',
function(err) {
console.log(err);
if (err) { throw err; }
}
);
I have this error:
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
But i can access the db via mongolab and :
mongo ds053419.mongolab.com:53419/jobinfest -u USER -p PASSWORD
I tried to create new users, even a new db. This way of connection seems to not work anymore
In your code be sure you are replacing USER:PASSWORD with your actual username and password.
mongodb://USER:PASSWORD#ds053419.mongolab.com:53419/jobinfest

Resources