Sivasankar chimata
Sivasankar chimata

Reputation: 341

node.js mysql count rows get value

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

Upvotes: 0

Views: 2382

Answers (2)

MaksymK
MaksymK

Reputation: 401

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

Upvotes: 2

Leonardo Drici
Leonardo Drici

Reputation: 789

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

Upvotes: 0

Related Questions