pg-pool throwing error after successful queries - javascript

I am trying to send post request to update state of a record in database. I'm using pg-pool to talk to database. My code is failing in the second query where I get 'This socket has been ended by other party'. Even though I get run state update response I still get the error.
router.post('/cancel', function(reg, res, next {
db.getclient('tasksys', function(err, client, done){
if(err){
done();
return next(err);
}
var statement = "select * from runs";
let runId;
client.query (statement, function(err, result){
done () ;
if(err)
return next(err);
} else{
runId = result.rows [0][' id']
var statement= "update runs set state 'pending' where id=$1";
var args = [runId];
client.query(statement, args, function(err, result){
done()
if(err){
return next(err);
}else{
return res.send('Run state updated')
}
});
}
});
});
});
Error:This socker has been ended by other party
at Scoket.writeafterFIN [as write]
at Connection.end(...connection.js)
at Client end(...lib/client.js)
atPool.remove (...pg-pool/index.js)
at Timeout(...pg-pool/index.js)
at listenOnTimeout(<node_internal/internal/timer.js)
at processTimers(internal/timers.js){code:'EPIPE', stack:'Error:This socket has been ended by the other party'}```

Related

Not getting a return object from a MySQL query in NodeJS

I'm making a logging system in NodeJS with MySQL DB. First I do the connection like this:
const con = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : 'dbpass',
database : 'dbname',
port : 3306,
multipleStatements : true
});
Then when I do a query to get users data I do the following query.
var user;
con.query('SELECT * FROM users WHERE email = ?', email, function(err, rows) {
if (err) throw err;
else {
user = rows[0];
}
});
But when I finally compare any of the fields of the user returned I get an error:
if (tools.hashPassword(password) == user.hash) {
// Do stuff
}
The error is TypeError: Cannot read property 'hash' of undefined. Any suggestion?
con.query("SELECT * FROM users WHERE email = ?", email, function (err, rows) {
if (err) {
throw err;
} else {
if (!rows.length) {
throw new Error("User not found");
}
const user = rows[0];
if (tools.hashPassword(password) == user.hash) {
// Do stuff
}
}
});
The fact is that you are getting the result, but it is asynchronous. Therefore at the time you check for user's property hash, the object itself has not loaded yet. You should put your comparison in the callback like this:
con.query('SELECT * FROM users WHERE email = ?', email, function(err, rows) {
if (err) throw err;
else {
if (tools.hashPassword(password) === rows[0].hash) {
// Do stuff
}
}
});
// This stuff happens usually BEFORE the query's callback,
// due to Node.js asynchronous nature

Nodejs creatng connection factory

Hi I have connection with db2 following way which works fine
require("ifxnjs").open(connectionString, function(err, con){
If(err){
console.log(err);
} else {
con.query(........){
}
}
});
I am trying to create a separate connection factory that can be called in any query. The code I have is
function confactory(){
db=require("ifxnjs).open(connectionString, function(err, conn){
if(err){} else {
console.log('connected');
}
})
return db
}
module.exports=confactory();
Than I access the connection in project
var db=require('./cofactory.js');
db.query('select * from emp', function(err, result){
if(err){}
else { cons
}
})
When I run the program I get error for
TypeError Can not read property 'query' of undefined
Please let me know how I can fix this issue. Thanks

Error when deleting from mySQL in node.js

I'm getting an error I don't understand when sending the parameters to my method, I thought my query was wrong but I did it manually and mySQL did what it had to do. So the problem is in my code but I don't seem to find where, thanks in advance.
exports.defav = function(id_user, id_restaurant, callback){
console.log(id_user + " " + id_restaurant); //Just making sure i'm reciving correclt
pool.getConnection(function(err, connection){
if(err){
console.log(err);
callback(true);
return;
}
connection.query("DELETE FROM favorites WHERE id_user = ? AND id_restaurant = ?", id_user, id_restaurant, function(err, results) {
console.log("SUCCESS: Removed from fav ");
connection.release();
if(err){
console.log(err);
callback(true);
return;
}
callback(results);
});
});
};
The error I'm getting is:
throw err; // Rethrow non-MySQL errors
^
TypeError: this._callback.apply is not a function
Query parameters should be passed in an array:
connection.query("DELETE FROM favorites WHERE id_user = ? AND id_restaurant = ?", [ id_user, id_restaurant ], function(err, results) {
...
});

Meteor JS - Nested Functions Returning Value not coming correctly

I am using Meteor.JS and pcel:mysql to fetch the mysql result from the method and passing it to the helper.
In my Method, the method is getting executed fine and using connection.query I am able to log the mysql rows in the server side console.
This is what my code looks like:
if (Meteor.isClient) {
Meteor.call('mysqltestcall1', function(error, result){
Session.set('myMethodResult', result);
});
Template.hello.helpers({
data2: function(){
return Session.get('myMethodResult');
}
});
}
if (Meteor.isServer) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'leaderboard'
});
connection.connect();
Meteor.methods({
'mysqltestcall1': function(){
var returnresult = 'test value';
connection.query('SELECT * FROM players', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
returnresult = rows;
});
return returnresult;
}
});
}
I am getting the value as "test value", but not rows JSON data. Can anyone help me out.
I thing I am not using the variable correctly is in the nested function.
Looks like connection.query is asynchronous, therefore it has not the time to be executed and the default "returnresult" is instantly returned.
What if you move the return statement in the query callback?
connection.query('SELECT * FROM players', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
return rows;
});

How get values out of a callback? (NodeJs + Mongoose)

I'm not too good with callbacks, and now I have problems to find a document with mongoose but use the document in the same action/controller before send a response.
uploadFile = function(req,res) {
var _objs = {};
function retrieveUser(objs,username, callback) {
User.findOne({ 'username': username })
.exec(function(err, user){
if(err) callback(err,null,null);
else callback(null,user,objs);
});
}//retrieveUser()
retrieveUser(_objs,req.body.user,function(err,user,_objs) {
if(err) console.log('ERROR: ' + err);
_objs.user = user;
console.log(_objs.user);
});
console.log(_objs);
}
So, inside the callback function the console.log() shows the object rightly, but the second console.log() shows me _objs as empty. Well, I need to fill _objs with other objects as attributes, How can I acchieve that?
Everything is working as designed. Your code will be executed as follows:
retrieveUser(_objs,req.body.user,function(err,user,_objs) {
// will be executed when the retrieveUser function completes is tasks...
if(err) console.log('ERROR: ' + err);
_objs.user = user;
console.log(_objs.user);
});
// ...meanwhile, execution will continue here.
console.log(_objs); // depending on how fast retrieveUser calls the callback, _objs will be set or (more likely) not set.
You can either continue the control flow of your application inside the callback or use frameworks like Streamline.js, async.js, Step, Seq, IcedCoffeeScript, promise.js, ...
Well this is what I did. At really for what I expected that is something similar to what I do in controllers in others frameworks of others languages, query for some entities and create another one that will be related to the previous that was queried.
uploadPic = function(req, res, next) {
var username = req.body.user,
estId = req.body.est;
async.series([
function(callback) {
User.findOne({ 'username': username})
.exec(function(err, user){
if(err) return callback(err);
if(!user) return callback(new Error("No user whit username " + username + " found."));
callback(null,user);
});
},
function(callback) {
Est.findById(estId)
.exec(function(err,est) {
if(err) return callback(err);
if(!est) return callback(new Error("No Est with ID " + estId + " found"));
callback(null,est);
})
},
],function(err,results){
if(err) return next(err);
console.log(results);
/// do my own stuffs here!
});// end async.series()
}

Categories

Resources