Error when deleting from mySQL in node.js - javascript

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) {
...
});

Related

pg-pool throwing error after successful queries

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'}```

ER_PARSE_ERROR you have an error in your SQL syntax: Selecting entire table from MySQL

I looked at similar questions first, but couldn't figure out how to change my code to get it working. I'm new to Node.js and MySQL. I'm running into this error:
My code is as follows (I am connecting okay, just changed host/pw info):
var mySQLpointer, connObj;
mySQLpointer = require("mysql");
connObj = mySQLpointer.createConnection( {
host: "host",
user: "user",
password: "pw",
database: "db"
} );
connObj.connect( function(err) {
if (err)
// throw err; or use the follwowing command
console.log("Connection Error: " + err.stack);
else
// console.log("Connected to DB. :-)");
console.log("Connection OK! ID = " + connObj.threadId);
});
let sqlStmt = "SELECT * FROM Product-Service";
connObj.query(sqlStmt,
function(err, dataSet, fields) {
if (err)
throw err;
else {
console.log(dataSet);
}
}
);
connObj.end();
What I'm trying to do is to display all rows and columns in my SQL table, I only have 3 rows in there:
Ideally, I'm trying to get them to display like this:
Any help would be appreciated.
You need backticks around your tablename, because of the -:
let sqlStmt = "SELECT * FROM `Product-Service`";

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

MongoClient not returning data in cucumberjs test

I've taken this apart several different ways. The find happens after the remove, and the find never finds anything. If I comment out the this.accounts.remove... the find works. If I leave the remove line in there it doesn't. My understanding of cucumberjs, mongo client and node indicates that the find should work.
I've even tried moving the remove/find sequence into its own file, and it works there. It seems to be only when I'm running it in cucumber that the sequence fails. I suspect because of the way of cucumber loads the files, but I'm not sure.
Can someone help me figure out how to get this working?
World.js:
var db = new Db('FlashCards', new Server('localhost', 27017));
db.open(function(err, opened) {
if (err) {
console.log("error opening: ", err);
done(err);
}
db = opened;
});
var {
defineSupportCode
} = require('cucumber');
function CustomWorld() {
this.db = db;
this.accounts = db.collection('accounts');
hooks.js:
Before(function(result, done) {
//comment this out, and leave a done(), it works!!!!
this.accounts.remove(function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
})
});
user_steps.js:
Then('I will be registered', function(done) {
let world = this;
this.accounts.find({
username: world.user.username
}).toArray(
function(err, accounts) {
if (err) {
console.log("Error retrieveing data: ", err);
done(err);
}
console.log("Accounts found: ", accounts);
expect(accounts).to.be.ok;
expect(accounts.length).to.be.equal(1);
done();
});
});
Inovcation:
cucumber-js --compiler es6:babel-core/register
You are missing the item to be removed in the remove method. I am assuming the item to be removed is
this.accounts.remove(function(error, result){
You are missing one parameter to remove method. The parameter is query to remove. I am assuming, the remove query is {username: world.user.username}
var qry={username: world.user.username};
Please try with the following:
Before(function(result, done) { //comment this out, and leave a done(), it works!!!!
var qry={username: world.user.username};
this.accounts.remove(qry, function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
}) });

async watefall doesn't call the functions

So i am actually woking on a simple program with node.Js and i have an issue using async.waterfall :
I created a function in my user model that connect the user by accessing the database, here is the code :
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
callback(err,null);
return;
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}
Using node-inspector i figured out that the main issue(I think) is that when it enters the waterfall function it doesn't execute the callback function of findOne it literally skips this and directly jump to the getPassword function (which isn't executed too).
so if someone could help me figuring out what's the problem that would be nice since i'm on it for around two days now.
Thank you
EDIT:
After adding the different missing cases of tests(which was why the callback didn't worked) I have this connection function:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
console.log('login: ',res.login);
console.log('erreur: ',err);
if (err){
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('login received :',userReceived.login);
var Ulogin = userReceived.login;
var Upassword = userReceived.password;
// function that compare the received password with the encrypted
//one
bcrypt.compare(password, Upassword, function(err, isMatch) {
if (err) {
console.log(err);
callback(err,null);
return;
}
else if (isMatch) {
console.log('Match', isMatch);
callback(null,isMatch);
}
else {
console.log('the password dont match', isMatch);
callback('pwd error',null);
}
});
},
], function(err){
if (err) {
console.error('unexpected error while connecting', err);
return false;
}
console.log('connected successfully');
return true;
});
}
And in my main file server.js i'm doing currently doing :
var connect = users.connection(login,password);
//the goal is to use the connect variable to know if the connection
//failed or not but it's 'undefined'
if(connect){
res.send('youyou connecté');
}
else {
res.send('youyou problem');
}
this absolutely don't work so i tried to use Q library but I have an error saying
"TypeError: Cannot read property 'apply' of undefined at Promise.apply"
here is the code using Q:
app.post('/signup', function (req, res) {
var login = req.body.login;
var password = req.body.password;
Q.fcall(users.connection(login,password))
.then(function (connect) {
if(connect){
res.send('connected');
}
else {
res.send('problem');
}
})
.catch(function (error) {
throw error;
})
.done();
});
but i am a little bit astonished i thought that by using async.waterfall() i told the function to wait until it received all the callbacks return so i don't understand why the connect variable is 'undefined'?
What I don't understand is - what was the flow exactly? did 'usersModel.findOne' get called?
What I see that is missing here in the getLogin function is a callback in the case that both the 'if' statement return false. in this case you'll get stuck in the first function and you won't advance to 'getPassword' function.
If this still doesn't work, please try executing the following code and report what was printed:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
if (err){
console.log('getLogin - error has occured');
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
console.log('getLogin - result seems OK');
// test a matching password if the user is found we compare both passwords
var userReceived = res.items[0].login;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('getPassword');
console.log(userReceived);
callback(null,'done')
}
], function(err){
if (err) {
console.error(err);
}
console.log('success');
});
}

Categories

Resources