node.js mysql count rows get value - mysql

Hi everyone i am using React-Native front end with Node.js with Mysql back end ,
I am counting the number of rows with particular id everything is good in the query, i got the value from the query but i am unable to use the value because it is in the the form of
"res_Count":[{"count(*)":2}] .
function i want it in the string format .
Once check my query and the result
router.get('/get_Following_Count/:user_id', (req, res, next) => {
connection.query("SELECT count(*) FROM followers WHERE followers.follower_id=? ORDER BY id DESC ", [req.params.user_id], (err, results, fields) => {
if (!err) {
// res.send(rows);
following_Count = JSON.parse(JSON.stringify(results));
return res.json({ "status": 200, "error": null, "res_Count": following_Count });
} else {
console.log(err);
return res.status(404).send('Sorry user_id does not exits');
}
})
});
Output:
{"status":200,"error":null,"res_Count":[{"count(*)":2}]}
Please give me any suggestions to change the count(*) value

try to change your query from
"SELECT count(*) FROM followers WHERE followers.follower_id=? ORDER BY id DESC"
to
"SELECT count(*) as followersCount FROM followers WHERE followers.follower_id=? ORDER BY id DESC"
and the use, for example
return res.json({ "status": 200, "error": null, "res_Count": following_Count[0].followersCount });

You could do this inside the route in express
router.get('/get_Following_Count/:user_id', (req, res, next) => {
connection.query("SELECT count(*) FROM followers WHERE followers.follower_id=? ORDER BY id DESC ", [req.params.user_id], (err, results, fields) => {
if (!err) {
// res.send(rows);
// CHANGES
following_Count = JSON.parse(JSON.stringify(results))[0];
-> REPLACE THIS COUNT(FIRST ONE) WITH WHATEVER YOU'D LIKE -> following_Count['count'] = following_Count['count(*)'];
delete following_Count['count(*)'];
//END CHANGES
return res.json({ "status": 200, "error": null, "res_Count": following_Count });
} else {
console.log(err);
return res.status(404).send('Sorry user_id does not exits');
}
})
}
The output will be
{"status":200,"error":null,"res_Count": {"count": 2} }
If you want the array back just delete the [0] and loop through each element and apply the logic of renaming the key

Related

Increment a value on MYSQL with react node.js

Why does this doesn't work
const increment = 'votes + 1'
db.query("UPDATE president SET votes = ? WHERE nickname = ?",
[increment, president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
but this code below works
db.query("UPDATE president SET votes = votes + 1 WHERE nickname = ?",
[president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
I just want to do the incrementing of mysql columns with votes = ?
I wanted to do it with the votes = ? way. Does anyone know the proper syntax of incrementing a value in mysql with react node js?

Nodejs: Unable to get query results and store in array

this is my code
const mysqlssh = require('mysql-ssh');
var Promise = require('promise');
const startSSHSQLTunnel = () =>{
return mysqlssh.connect(
{
host: 'xxx.xxx.xx.xxx',
user: 'ball',
password: 'r252_bat'
},
{
host: '192.xxx.xxx.xxx',
user: 'portal',
password: 'r252_bat',
database: 'mydb'
}
)
}
exports.getSignupSummary = async() => {
let res = []
let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
'SELECT COUNT(*) as count from `chatbots`']
//SELECT COUNT(*) as count from `chatbots`;
getUserData = function(qs, cb) {
startSSHSQLTunnel().then(client => {
client.query(qs,
function(err, results) {
if (err)
return cb(err);
cb(undefined, results);
})});
}
// Usage:
queryStrings.map(x => {
getUserData(x,
function(err, results) {
res.push(results);
}
)
});
console.log(res);
}
I am trying to get the query results and store in an array called "res"
however I am facing the following issues
the results from the callback function can be console.logged but if I store in array and then try to print it out, I see an empty array.
I tried to use async -> await but it was no use
I tried to encapsulate everything in a new promise and then resolve the results but that was no point as I got an empty promise
please advise
You should try something like this:
exports.getSignupSummary = async() => {
let queryStrings = ['SELECT year, WorkWeek, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, WEEK(signed_up) as WorkWeek from `chatbots` where signed_up is not null) temp_table group by WorkWeek, year',
'SELECT year, WorkMonth, COUNT(*) AS Count from (SELECT YEAR(signed_up) as year, MONTH(signed_up) as WorkMonth from `chatbots` where signed_up is not null) temp_table group by WorkMonth, year',
'SELECT COUNT(*) as count from `chatbots`']
//SELECT COUNT(*) as count from `chatbots`;
getUserData = function(qs, cb) {
startSSHSQLTunnel().then(client => {
client.query(qs, function(err, results) {
if (err) return cb(err);
cb(undefined, results);
});
});
}
// Usage:
const promises = queryStrings.map(x => {
return new Promise((resolve, reject) => {
getUserData(x, function(err, results) {
if (err) reject(err);
resolve(results);
});
});
});
const res = await Promise.all(promises);
console.log(res);
}
This code uses the .map function to create a promise for each of your queries and store it in an array.
Then we use await Promise.all to wait for all the promises to be resolved.

Node.js - getting a value from MySQL and assigning it to a variable

My query:
pool.query("SELECT MAX(ID) FROM `games` WHERE status IN('0','1') LIMIT 1", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0];
console.log(currentGame);
});
Current Result:
RowDataPacket { 'MAX(ID)': 1 }
Desired Result:
1
How do I get just the value and not include the other stuff?
Try adding an alias to your count query, and then access it:
pool.query("SELECT MAX(ID) AS max_id FROM games WHERE status IN ('0','1')", (err, row) => {
if(err) return console.log("err getting the game.");
currentGame = row[0].max_id;
console.log(currentGame);
});
Note: A max query by definition will always return only a single record result set (in the absence of GROUP BY), so there is no need for LIMIT 1.

My Sql query return an empty array with req.params.id in nodejs

I have i Mysql query with nodejs like this :
application.get('/Modification/:idt',function(req,res){
connection.query("SELECT * FROM memos WHERE idMemo = 'req.params.idt'",function (error, rows){
if (error) {
console.log("error ocurred",error);
}
else {
console.log(req.params.idt);
console.log(rows);
var no = rows;
res.render('memosModif.ejs', {no});
}
});
});
and my query return an empty array even if req.params.idt return an int value like 1 or 2 ... , but when i replace req.params.id with a int like 1 or 2 ... the query returns the right result
i dont understand why and how to fix that .
You are comparing the idMemo column to the string literal 'req.params.idt'. Instead, you should bind the value from this variable:
connection.query("SELECT * FROM memos WHERE idMemo = ?", req.params.idt, function (error, rows) {

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.