How to check if mongos connection still alive in Node.JS? - javascript

Let's imagine we have Node.JS app which is connecting to the Mongos process. But suddenly Mongos failed. How our app could now about it?
var db = null;
mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb) {
if(err) throw err;
db = mydb
});
..... on response we have .....
db.collection('test_collection', function(err, collection){
collection.find({}).toArray(function(err, documents){
// doing some work here
// but if Mongos failed, we are blocked on this stage
});
});

Would you not want to do the same thing that you're doing at connect, but within the function?
i.e.
...
collection.find({}).toArray(function(err, documents) {
if(err) {
throw err; //or do something equivalent. It doesn't really matter if the connection has failed, as it will still throw an error.
} else {
///continue processing
}
....
Alternatively, if you use a 3rd party mongo manager, such as mongoose, you can do something like this globally:
mongoose.connect('mongodb://' + config.mongo.host + '/' + config.mongo.db);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error: '));

Related

Unable to add array data to MongoDB collection

I have 2 URLs, one points to a different connection string and the other to local MongoDB instance. While I establish the connection to MongoDB using MongoClient with url1 and fetch the required data from a DB/collection and lastly store it in an array.
Now I want to insert this array to a localhost MongoDB collection and on doing so I get MongoError: Topology is closed, please connect error.
app.js
var url1="someurl but not localhost";
var url2="mongodb://localhost:27017/";
router.get('/route1', function(req, res)
{
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("customer");
dbo.collection("customer_report").find({}).toArray(function(err, result) {
if (err!=null){
console.log("Connection Failed!!"+err)
}
var customerArray =[];
for(i=0;i<result.length;i++){
backupArray.push({
a: result[i].a,
b: result[i].b,
c: result[i].c,
d: result[i].d,
});
}
console.log(customerArray);
res.json({content:customerArray});
db.close();
MongoClient.connect(url2,{ useUnifiedTopology: true }, function(err, db1) {
//Trying to establish another mongodb connection wuth new url
if (err) throw err;
var dbo = db.db("localdb");
dbo.collection("localcollection").insertMany(customerArray, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db1.close();
});
});
});
});
});
And if I don't close db.close(); then the array data gets appended to first MongoDB collection and not the local MongoDB. Looking for a solution to handle two MongoClient at the same time or a way to insert the customerArray to local MongoDB collection.
Is there a workaround where I can add the array elements to my local MongoDB collection?
In your second mongo connect block I think you want
var dbo = db.db("localdb");
to be
var dbo = db1.db("localdb");
Have you made sure those credentials work in console commands? And have you made sure the last connection through the console is closed before trying to use them in the script?

Error: Connection lost: The server closed the connection. Nodejs / mysql

I am having a few issues with one route that I am looking at...
app.get('/newusersvariables', function(req, res) {
const sessionid = req.session.id;
//let newuser = mysql.createConnection(mysqlconfig);
let connection = mysql.createConnection(mysqlconfig);
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM user_idpdetails WHERE sessionid = ?", [sessionid], function (err, result, fields) {
if (err) throw err;
console.log(result);
connection.end();
});
});
I have tried moving around the connection.end but to no avail. In some situations, I get connection lost, as if it is ignoring the connection end. And if I move it to other places then I am getting
'Error: Cannot enqueue Query after invoking quit.'
It is most likely something simple that I am overlooking as I am new to node.

How can i pipe mysql data to a browser window instead of the console in Nodejs?

Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});

Express: Accessing req.session from /models/index.js

I've built a series of database queries in my express app that reside in a /models/index.js file which I can access from app.js via var express = require('express');. I am trying to populate req.session.user with a userid that is returned by a findByEmail(); function in /models/index.js.
The findByEmail(); function works fine, however I can't figure out how to store its return value in req.session. I've tried including req.session.id = result.rows[0].id; in the 'findByEmail();function, but this returns areq is not defined` error.
Am I overlooking a simple require statement in my /models/index.js file or is there another trick to accessing req.session in a module?
I've included the relevant code from /models.index.js below:
/models.index.js:
var pg = require('pg');
function findByEmail(email){
pg.connect(function(err, client, done) {
if(err) {
console.log('pg.connect error');
throw err;
}
client.query('BEGIN', function(err) {
if(err) {
console.log('client.query BEGIN error');
return rollback(client, done);
}
process.nextTick(function() {
var text = "SELECT * FROM users WHERE email = $1";
client.query(text, [email], function(err, result) {
if(err) {
console.log(err);
return rollback(client, done);
}
console.log(result);
console.log(result.rows);
console.log('id: ', result.rows[0].id);
req.session.id = result.rows[0].id;
done();
});
});
});
});
}
module.exports.pg = pg;
exports.findByEmail = findByEmail;
As far as /models/index.js knows, req is not defined, same thing with rollback. A module is a closure and you don't have access to variables defined outside of it.
If you want to do that you must pass them as parameters but it's not very good design, as #gustavohenke said: Separation of concerns.
You might want to have a callback and call it with success/error and set the session id there so you don't have to pass in into the module:
function findByEmail(email,callback){
pg.connect(function(err, client, done) {
if(err) {
console.log('pg.connect error');
throw err;
}
// Do all the async work and when you are done ...
// An error is usually passed as the first parameter of the callback
callback(err,result)
});
}
exports.findByEmail = findByEmail;
You would then call it like this:
var models = require('./models');
models.findByEmail('thedude#lebowski.com',function(err,results) {
// set session id here where you probably have access to the req object...
})

how to check monogdb database connection

Working with Node.js(monogdb, express and other modules)
I'm wondering if there is a mongoose method for database connection, something like if I open a connection var db = mongoose.connect('mongo://localhost/members'); then I can db.on('close', function(){ /*do stuffs here*/}).
Basicly, the function below does the job of getting a user list from database and logging when database connection is closed.
So I need something in the if() to check database connection or whatever just unable to get data while its off and make a logging. I tried if(docs != null) it seems just off tho. Any advice would be much appreciated!
var logger = require('bunyan');
var log = new logger({
name: "loggings",
streams: [
{
level: 'error',
path: 'test.log',
}
],
serializers: {
err: logger.stdSerializers.err,
}
});
function(req, res){
memberModel.find(function(err, docs){
if (/*connection is closed*/) {
res.render('users.jade', { members: docs });
}else{
try {
throw new DatabaseError ("Error!");
} catch (err){
log.warn({err: err}, "Check database connection!");
}
res.render('index.jade');
};
});
};
Why are you checking in the place you are for the database connection being closed? If it is closed at that point, then it is likely that docs will be null. I think checking
if (!err) {
res.render('users.jade', { members : docs });
} else {
/* throw err, etc */
is a reasonable course to take.
Since you want to log when the database connection is closed, why not attach a logging function to the Db's "close" event?
If I've misunderstood and checking for the connection's state is what you really want, then I'd recommend playing around with the properties of:
http://mongoosejs.com/docs/api.html#connection_Connection
(hit the "show code" button). The connection's _closeCalled property looks like it may be what you want to check.
You can use mongoose events that will get fire whenever your server get disconnected:
mongoose.connection.on('error', function (err) {
console.log('Mongoose default connection error: ' + err);
//HERE SERVE YOUR DISCONNECT WARNING PAGE AND LOGGER
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
//HERE SERVE YOUR DISCONNECT WARNING PAGE AND LOGGER
});
var uri = 'mongodb://localhost/user1';
var promise = mongooose.connect(uri,{
useMongoClient: true,
});
promise.openUri(uri,function(errr,db){
if(errr){
throw errr;
}else{
console.log("Connection Successfull");
glo_db = db;
}
});
Above could needs to be written for the newer version of mongoose and would throw error if any error is found while connecting to a database.
Check here

Categories

Resources