node.js mysql query update from an array - mysql

i am beginner in node.js , i hava an array of json data and i wanted to update my table squad by all the rows of my json array , so i used a loop , and then after i execute , i can only see the json input with console.log(data.players) but there is no response or anything , like the function is dead , no errors , the update is not done , just displaying the entry data
Here the input data:
{"id":1,"email":"d","password":"d","name":"d","price":5,"points":5,"fixture":"d","userid":1,
"players":
[{"id":2724,"firstname":"Lucas Digne","lastname":"Lucas Digne","position":"D","price":0,"rating":"7.3","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2724.png","teamid":45,"clubid":1,"fixtureid":592848,"points":2},{"id":19599,"firstname":"Emiliano Martínez","lastname":"Emiliano Martínez","position":"G","price":0,"rating":"6.6","appearences":1,"goals":0,"assists":0,"cleansheets":5,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/19599.png","teamid":66,"clubid":1,"fixtureid":592855,"points":11},{"id":2741,"firstname":"Mathew Ryan","lastname":"Mathew Ryan","position":"G","price":0,"rating":"5.0","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2741.png","teamid":42,"clubid":1,"fixtureid":592851,"points":-1},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":289,"firstname":"Andrew Robertson","lastname":"Andrew Robertson","position":"D","price":0,"rating":"7","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/289.png","teamid":40,"clubid":1,"fixtureid":592850,"points":2},{"id":2726,"firstname":"Kurt Zouma","lastname":"Kurt Zouma","position":"D","price":0,"rating":"7.2","appearences":1,"goals":0,"assists":0,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/2726.png","teamid":49,"clubid":1,"fixtureid":592851,"points":2},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5},{"id":633,"firstname":"İlkay Gündoğan","lastname":"İlkay Gündoğan","position":"M","price":0,"rating":"8.3","appearences":1,"goals":0,"assists":1,"cleansheets":0,"redcards":0,"yellowcards":0,"image":"https://media.api-sports.io/football/players/633.png","teamid":50,"clubid":1,"fixtureid":592852,"points":5}]}
Here the node.js:
updatefixture:(data,callback)=>{
console.log(JSON.stringify(data));
for(var item of data.players){
pool.query(
'UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
],
);
}
(error,result) => {
if(error){
console.log(error);
return callback(error);
}
return callback(null,result);
}
},
I just want a way to update all rows with the condition that made with where clause and make sure that the rows will be updated, any help for a beginner like me will be so appreciated

It seems you just moved callback of pool.query function outside of the loop.
Try the following:
updatefixture:(data,callback)=>{
function addPlayer(item) {
return new Promise((accept, reject) => {
pool.query('UPDATE squad SET appearences = 1, rating = ? goals = ? assists = ? , cleensheets = ?, redcards = ?, yellowcards = ? , points = ? WHERE id = ? AND fixtureid = ? ',
[
item.id,
item.rating,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.points,
item.id,
item.fixtureid
], (error, result) => {
if(error){
reject(error);
} else {
accept(result);
}
});
});
}
console.log(JSON.stringify(data));
Promise.all(data.players.map(addPlayer)).then((result)=>{
console.log(result)
callback(null, result)
}).catch((error)=>{
console.log('Error:', error)
callback(error)
})
},

Related

Getting a function out of a query

I'm trying to get a variable out of a query as shown below, thanks in advance
var deutsch_meund_note = "";
connection.query(
'SELECT count(*) as sum FROM noten WHERE id = ? and fach = ?',
[id, "mathe"],
function(error, results, fields) {
if (error) {
console.log("no deutsch_schr for id: "+ id);
} else {
const deutsch_meund_viel = results[0].sum;
connection.query(
'SELECT SUM(note) as sum FROM noten WHERE id = ? and fach = ?',
[id, "deutsch_meund"],
function(error, results, fields) {
const deutsch_meund_insge = results[0].sum;
const deutsch_meund_note = deutsch_meund_insge / deutsch_meund_viel;
//this variable: **var deutsch_meund_note = deutsch_meund_note;**
});
}
});
I need to get the variable out of the "connection.query" function but when I try it like the example above it just says "undefined"

Mysql, Node, query within a query, how to populate property in map function from another query

Firstly, if anyone can edit my question title or question to make more sense, please do.
I have a node/express app making mysql queries with mysql.js. I have a query that looks up a table of questions and then runs a map function on the results. Within that map function, I need to query another table, of answers, corresponding to each record in the questions table. The value I need is the number of answers to that question, ie the number of records in each answers table. I've tried all kinds of different examples, but nothing quite fits my case in a way that makes sense to me. New at Node and Express, and even MySQL so having a hard time picking out quite what to.
I understand that the problem is the async nature of node. getAnswersCount() returns "count" before the query finishes. Below is my code. Need some advice on how to achieve this.
The value 123 is assigned to count just to clarify the trace results.
app.get('/', (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
answers: getAnswersCount( q.id )
}));
res.send( questions );
});
});
const getAnswersCount = ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( count ); // will=123
count = results[0].answersCount;
//console.log( count ); // will = results[0].answerCount
});
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
EDIT: After attempting various versions of Michael Platt's suggestion in his answer without success, I finally worked out a solution using Express callbacks and a promise, adding the answers values to the questions array afterwards:
app.get( '/', (req, res, next ) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => ({
id: q.id,
title: q.title,
description: q.description,
}));
next();
});
}, (req, res ) => {
questions.map( currentElem => {
getAnswersCount( currentElem.id ).then( rowData => {
currentElem.answers = rowData[0].answersCount;
if( currentElem.id == questions.length ) res.send( questions );
});
});
});
const getAnswersCount = ( id ) => {
const tableName = 'answers_' + id;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
db.query( sql,
(error, results) => {
if (error) throw error;
//console.log( 'answers table created!' );
});
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
return new Promise( ( resolve, reject ) => {
db.query( sql, ( error, results ) => {
if ( error ) return reject( err );
resolve( results );
});
});
}
I'm not sure which database module you are using to connect to and query the database but you could make the method async and then await the response from the query like so:
const getAnswersCount = async ( id ) =>
{
const tableName = 'answers_' + id;
var count = 123;
var sql = `CREATE TABLE IF NOT EXISTS ${tableName}(
id int primary key not null,
answer varchar(250) not null
)`;
var results = await db.query(sql);
sql = `SELECT COUNT(*) AS answersCount FROM ${tableName}`;
var count = db.query(sql)[0].answerCount;
// I know this code runs before the query finishes, so what to do?
//console.log( count ); //still 123 instead of results[0].answersCount
return count;
}
app.get('/', async (req, res) => {
db.query('SELECT * FROM questions LIMIT 0, 100',
(error, results) => {
if (error) throw error;
questions = results.map(q => {
const answerCount = await getAnswersCount( q.id )
return {
id: q.id,
title: q.title,
description: q.description,
answers: answerCount
}
}));
res.send( questions );
});
});
I think that will give you what you want and run correctly but it might require a bit of tweaking. You may need to async the function on the actual route itself as well and await the call for getAnswersCount but that should just about do it.

Ignore update data if exist in mysql by node js

I'm going to check id of my data if exist in mysql update it and if not create it, but in select result it dosen't work and go to esle section and create action most of the times and got Duplicate entry error. at the end I run this file by infinite loop.
I should tell this when I have a lot data in redis this problem will happen.
I'll be glad if help me, thanks :)
Here is my code :
var
mysql = require('mysql'),
redis = require('redis'),
infiniteLoop = require('infinite-loop'),
client = redis.createClient(),
lop = new infiniteLoop,
config = require( __dirname + '/app/Config').config,
con = function() {
return mysql.createConnection({
host : config.db_host,
user : config.db_user,
password : config.db_pass,
database : config.db_name
});
},
insertDB = function( data ) {
var connection = con();
connection.connect( function( err ) {
connection.query( 'SELECT * FROM real_user WHERE id =' + data.id, function( err, res ) {
if ( err ) {
data = JSON.stringify(data);
client.lpush('aipi', data, function(err,reply) {
if ( err ) throw err;
});
}
console.log( "out", data.id, res.length, res );
if ( typeof res != 'undefined' && res.length > 0 ) {
console.log( "update", data.id );
connection.query( 'UPDATE real_user SET ? WHERE id =' + res[0].id, { request_count: data.request_count, updated_at: data.created_at },
function( err, res ) {
if ( err ) throw err;
});
} else {
console.log( "create", data.id );
connection.query( 'INSERT INTO real_user SET ?', data, function( err, res ) {
if ( err ) throw err;
});
}
connection.end();
});
});
},
run = function() {
var data;
client.brpop('aipi', 0, function(err, reply) {
if ( reply[1] ) {
data = JSON.parse(reply[1]);
insertDB(data);
}
});
};
lop.add(run, []).run();
Fixed it by :
ON DUPLICATE KEY UPDATE
connection.connect( function( err ) {
connection.query( "INSERT INTO real_user SET ? ON DUPLICATE KEY UPDATE updated_at = '" + data.created_at
+ "', request_count = '" + data.request_count + "'",
data, function( err, res ) {
connection.end();
});
});

perform async multiple Mysql queries on Node

I'm using node with Mysql and here's my problem.
I'm trying to add new photos on my database and return it as an array
here is my function :
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = []
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
});
}
})
})
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise}
The Insert works well but i can't retrieve the results to send them back to the client. (my array is empty)
Thanks.
Always promisify at the lowest level, in this case db.connection.query().
if(!db.connection.queryAsync) {
db.connection.queryAsync = function(sql, data) {
return Q.Promise(function(resolve, reject) { // or possibly Q.promise (with lower case p), depending on version
db.connection.query(sql, data, function(err, result) {
if(err) {
reject(err);
} else {
resolve(result);
}
});
});
};
}
Now the higher level code becomes very simple :
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
});
}));
};
To prevent a single failure scuppering the whole thing, you might choose to catch individual errors and inject some kind of default ;
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?',
defaultPhoto = /* whatever you want as a default string/object in case of error */;
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
}).catch(function() {
return defaultPhoto;
});
}));
};
Do the return in your async loop function when all has been done
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = [];
var todo = files.length;
var done = 0;
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise
}
});
}
else
{
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise;
}
}
})
})
}

How to update multiple columns in mysql using nodejs

How to update the multiple columns in MySQL using node.js:
var query = 'UPDATE employee SET profile_name = ? WHERE id = ?';
connection.query(query,[req.name,req.id] function (error, result, rows, fields) {
but I have to update profile_name, phone,email, country, state, address at once.
How can I do that, can anyone suggest.
Simply add all columns in set:
var query = 'UPDATE employee SET profile_name = ?, phone =?, .. WHERE id=?';
connection.query(query,[req.name,req.phone,...,req.id] function (error, result, rows, fields) {
👨‍🏫 To update your multiple columns in mysql using nodejs, then You can do it like this code below: 👇
const query = 'UPDATE `employee` SET ? WHERE ?';
connection.query(query, [req.body, req.params], function(err, rows) {
if(err) {
console.log(err.message);
// do some stuff here
} else {
console.log(rows);
// do some stuff here
}
});
💡 Make sure your req.body is not empty and the field in your req.body it's same with the field in your employee table.
If your req.body is undefined or null, then you can add this middleware to your express server:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
I hope it can help you 🙏.
UPDATE statement syntax :
UPDATE <TableName>
SET <Col1> = <Val1>,
<Col2> = <Val2>,
....
WHERE id = ?
If you have multiple columns update, and need to take the values from the Object,
you can do the following-
let data = {
"table": {
"update_table":"dlrecustomer"
},
"result": {
"pro":"blre",
"pro_id":"BFCA",
"MOBILE":"9506443333",
},
"keys": {
"CUSTOMER":"27799144",
"APPLICATION":"5454642463"
},
}
let update_set = Object.keys(data.result).map(value=>{
return ` ${value} = "${data.result[value]}"`;
});
let update_query = `UPDATE ${data.table.update_table} SET ${update_set.join(" ,")} WHERE CUST_ID = "${data.keys.CUSTOMER}" AND APPL_ID = "${data.keys.APPLICATION}"`;