Trying to connect mLAB DB from localhost server? Authentication failed - json

Below is the code Snippet :
var mongoose = require('mongoose');
//mongodb://localhost/db
mongoose.connect('mongodb://username:pwd#ds117859.mlab.com:17859/db');
var db = mongoose.connection;
Now when I connect to localhost server, it works fine and I am able to perform operations on local Mongo DB
But when I connect to my db on MLAB, I get the following error:
$ node app.js
Server started on port 3000
(node:8648) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Authentication failed.
When I print the error object I get this :
err { MongoError: Authentication failed.
at C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:595:61
at authenticateStragglers (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:513:16)
at Connection.messageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:549:5)
at emitMessageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:309:10)
at Socket.<anonymous> (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:452:17)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20)
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }

//replace username,password and databasename
var mongoose = require('mongoose');
var mongodbUrl = "mongodb://username:password#ds153869.mlab.com:53869/databasename";
mongoose.connect(mongodbUrl, { useNewUrlParser: true });
mongoose.connection.on("connected", function(){
console.log("mongoose database connected with " + mongodbUrl);
});
mongoose.connection.on("error", function(err){
console.log("Unable to connect with " +mongodbUrl + "error are"+ err);
});

Related

Calling a function in a callback function in NodeJs

I am trying to implement this solution to my code. However, I am having trouble trying to call a function in a callback function.
In my index.js file, I have this
const db = require('./models/db.js');
db.connectDb();
In my db.js file, I have the following:
const mysql = require('mysql');
const database = {
//Connects to the DB
connectDb : function () {
// Create connection
this.db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'example'
});
this.db.connect(function(err){
if(err){
console.log("An error has occured when trying to connect to db.");
throw err;
}
console.log("MySQL Connected...");
});
this.db.on('error', function (err) {
var currentdate = new Date();
consoleoccurredn error has occured # ', currentdate,' with error:', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
this.handleDisconnect();
} else {
throw err;
}
});
},
handleDisconnect: function () {
this.connectDb();
}
}
module.exports = database;
The server starts up and MySQL connection has been successfully created. Since my intention is to handle the error connection lost, I restarted the server, and as expected, this.db.on('error', function (err) is executed, as reflected in the terminal.
MySQL Connected...
An error has occurred # [datetime] with error: Error: Connection lost: The server closed the connection.
at Protocol.end (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (node:events:538:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
However, I get this error:
/home/folder/models/db.js:27
this.handleDisconnect();
^
TypeError: this.handleDisconnect is not a function
at Connection.<anonymous> (/home/folder/models/db.js:27:22)
at Connection.emit (node:events:526:28)
at Connection._handleProtocolError (/home/folder/node_modules/mysql/lib/Connection.js:423:8)
at Protocol.emit (node:events:526:28)
at Protocol._delegateError (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:398:10)
at Protocol.end (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:116:8)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (node:events:538:35)
at endReadableNT (node:internal/streams/readable:1345:12)
[nodemon] app crashed - waiting for file changes before starting...
My question: Does this error have to do with trying to call a function outside of a callback function? Is it possible to call a function outside of a callback function, and that callback function is inside an object's function? Or is the problem something else?
For your reference, here is what is outputted in the terminal.
MySQL Connected...
An error has occurred # [datetime] with error: Error: Connection lost: The server closed the connection.
at Protocol.end (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (node:events:538:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
/home/folder/models/db.js:27
this.handleDisconnect();
^
TypeError: this.handleDisconnect is not a function
at Connection.<anonymous> (/home/folder/models/db.js:27:22)
at Connection.emit (node:events:526:28)
at Connection._handleProtocolError (/home/folder/node_modules/mysql/lib/Connection.js:423:8)
at Protocol.emit (node:events:526:28)
at Protocol._delegateError (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:398:10)
at Protocol.end (/home/folder/node_modules/mysql/lib/protocol/Protocol.js:116:8)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/home/folder/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (node:events:538:35)
at endReadableNT (node:internal/streams/readable:1345:12)
[nodemon] app crashed - waiting for file changes before starting...
The problem calling this.handleDisconnect() in this code:
this.db.on('error', function (err) {
var currentdate = new Date();
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
this.handleDisconnect();
} else {
throw err;
}
});
is that the value of this is not what you need it to be and that's why you get the error that this.handleDisconnect is not a function (it's probably undefined). A plain function callback will set its own value of this according to how the caller (which is your database) calls it. Instead, you can change it to an arrow function and it will retain the desired value of this. This is the main reason that arrow functions were invented (to preserve the lexical value of this):
this.db.on('error', (err) => {
var currentdate = new Date();
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
this.handleDisconnect();
} else {
throw err;
}
});
Another problem here is that throw err in this context will not be useful. You will throwing back into some asynchronous context in your database and that's not anywhere that you can catch or handle that error or do anything useful with it. So, you will need a more useful way to process that error.

The mysql server disconnects every night, how do I resolve it?

I leave my computer on 24 hours, but I still lose connection with the MySQL server. My WiFi runs smoothly and is never disconnected because I'm still able to use the internet along with my other electronics. The error message says
The server closed the connection.
Is this inferring a problem on my computer/connection or with MySQL? Or is it my codes? Please advise.
Error messages:
events.js:174
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:525:10)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
at Connection._handleProtocolError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:426:8)
at Protocol.emit (events.js:198:13)
at Protocol._delegateError (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\Nick\Desktop\MyBot\node_modules\mysql\lib\Connection.js:97:28)
[... lines matching original stack trace ...]
at process._tickCallback (internal/process/next_tick.js:63:19)
My codes:
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: 'db',
dateStrings: 'date',
});
const handleDisconnect = () => {
con.connect(err => {
if (err) throw err;
console.log("Connected!");
});
con.on('err', err => {
console.log('db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});
}
handleDisconnect();

Connection lost The server closed the connection - Cannot enqueue Query after fatal error

I got an error once that the TCP connection is shut down by the server. The error looks the same as this question has
Error: Connection lost: The server closed the connection.
at Protocol.end (/opt/node-v0.10.20-linux-x64/IM/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:79:10)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
So to solve this problem I used the answer posted in this question. I did this
var mysql = require('mysql');
var db_config = {
host : 'localhost',
user : 'xxxx',
password : 'xxxx',
database : 'xxxx'
}
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else {
console.log('error is err:', err); // connnection idle timeout (the wait_timeout
// throw err; // server variable configures this)
}
});
}
handleDisconnect();
module.exports = connection;
My program never crashes until today when I face some issue like user was not getting the notifications. since it has to do with the database. So when I checked the log files. this was the error
sql error isError: ER_QUERY_INTERRUPTED: Query execution was interrupted
db error { Error: Connection lost: The server closed the connection.
at Protocol.end (/var/www/html/mysite/node/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/var/www/html/mysite/node/node_modules/mysql/lib/Connection.js:97:28)
at Socket.<anonymous> (/var/www/html/mysite/node/node_modules/mysql/lib/Connection.js:502:10)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }
error when connecting to db: { Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:992:11)
at _exceptionWithHostPort (util.js:1014:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1186:14)
and then it keeps printing this above error in my log files and along with this as well
Cannot enqueue Query after fatal error.
Please help me to solve this problem. I have to do a restart the server to make it work

How to provide SERVICE_NAME in the connection options in mysql npm?

I have a JDBC connection string something like this
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=OFF)(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1711))(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=1712)))(CONNECT_DATA=(SERVICE_NAME=servicename)(SERVER=DEDICATED)))
I have created the connection as
var connection = mysql.createConnection({
host: "hostname",
port: "1711",
user: "user",
password: "password"
});
How do I also provide SERVICE_NAME (like the jdbc string) to the connection options?
I am getting the following error without it:
Error: connect ECONNREFUSED <some_ip>:1711
at Object.exports._errnoException (util.js:1028:11)
at exports._exceptionWithHostPort (util.js:1051:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
--------------------
EDIT:
Changing the port to 1712 gives me a different error after taking a lot of time.
Error: Connection lost: The server closed the connection.
at Protocol.end (..\node_modules\mysql\lib\protocol\Protocol.js:113:13)
at Socket.<anonymous> (..\node_modules\mysql\lib\Connection.js:109:28)
at emitNone (events.js:91:20)
at Socket.emit (events.js:186:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
EDIT: Sorry. I didn't see the database was oracle and started trying mysql directly.
I am assuming that your mysql server is running on port 1711 not default port.
And if you are getting Connection lost error mean there are something wrong on your network try to reconnect your server after sometime.
var conn;
function handleDisconnect() {
conn = mysql.createConnection(//your config);
conn.connect(function(err) {
if(err) {
console.log('error when connecting to database:', err);
setTimeout(handleDisconnectConnection, 5000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnectConnection();
} else {
throw err;
}
});
}
handleDisconnectConnection();
Hope that will work for you

Node and MySQL connection to database

I need t o provide the MySQL connection for modules, so I provide the code like this:
var express = require('express');
var mysql = require('mysql')
var app = express();
var connection = mysql.createConnection({
host: '149.xxx.xx.x',
user: 'User',
password: 'Password',
database: 'DataBase',
port: 1443,
});
connection.connect(
function(error) {
console.log(error.code); // 'ECONNREFUSED'
console.log(error.fatal); // true
console.log(error.sql);
console.log(error.sqlMessage);
}
);
and after some time (about 1-2 minutes) I received an error from those console.logs:
ECONNRESET
true
undefined
undefined
I think maybe it's the timeout because of my "nonactivity", but when I'm trying to do the query the errors are the same.
Have any idea what is wrong? I checked it from DataGrip and the data are correct.
Ok, I found one small bug here. The database is MS SQL Server (microsoft). I'm trying now using the library called mssql to connect to that database, provide some code:
var config = {
server: "149.xxx.xx.x",
database: "Database",
user: "User",
password: "Password",
connectionTimeout: 300000,
requestTimeout: 300000,
pool: {
idleTimeoutMillis: 300000,
max: 100
}
};
function getEmp() {
var connection = new sql.Connection(config);
var req = new sql.Request(connection);
connection.connect(function (error) {
if(error) {
console.log(error);
return;
}
req.query('Procedure', function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
connection.close();
});
});
}
getEmp();
and I receive the error:
{ ConnectionError: Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433
at Connection.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/mssql/lib/tedious.js:353:25)
at Connection.g (events.js:292:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:791:12)
at Socket.<anonymous> (/Users/phuzarski/Learning/NodeJS/srv-express/node_modules/tedious/lib/connection.js:33:15)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
name: 'ConnectionError',
message: 'Failed to connect to 149.xxx.xx.x:1433 - connect ETIMEDOUT 149.xxx.xx.x:1433',
code: 'ESOCKET' }
For sure the data are correct- DataGrip is connecting fine here.
I found at google the similar problem, the problem was Disabled TCP/IP. I checked this one and it's Enabled with this port 1443.