I am trying to connect my database to my web app and I can get the data to show up how I want it to. I am getting too much information.
The code I have tried is this:
var express = require("express");
var router = express.Router();
const mysql = require('mysql')
const connection = mysql.createConnection({
host: '',
user: '',
password: '',
database: ''
})
connection.connect()
router.get("/", function(req, res, next) {
connection.query ('SELECT countnum FROM countrecord',
function (err, rows){
if (err) console.log(err)
var string = JSON.stringify(rows)
res.send(JSON.parse(string)
}
);
});
module.exports = router;
Though I do have the database information in the create connection.
When I send the data to the webapp and API, I get this:
[{"countnum":1},{"countnum":5},{"countnum":6},{"countnum":7},
{"countnum":15},{"countnum":15},{"countnum":15},{"countnum":15},
{"countnum":15},{"countnum":15},{"countnum":15},{"countnum":15},
{"countnum":15},{"countnum":15},{"countnum":15},{"countnum":15},
{"countnum":15},{"countnum":15},{"countnum":8},{"countnum":20},
{"countnum":8},{"countnum":166},{"countnum":155},{"countnum":155}]
But I only want the numbers so I can iterate through them and work with them. I have tried so many other things and either I get errors or I get undefined, so I don't get anything showing up. Help with this would be greatly appreciated as I am very lost.
CodePudding user response:
While this is not an optimal solution, what you can do is this:
string.map((value) => value["countnum"]);
this will give you an array of numbers.
Ideally, you should tweak your SQL query the way, so it'd return you numbers only.
CodePudding user response:
The 'rows' variable is the result of your query in the form of an array whose each element represents a row in your 'countrecord' table, and consists, for each column defined by the SELECT part of your query, of a column name/value pair.
If you want replace this pair to get only the value of the 'countnum' column for each row of the table, you need to use the Array.map function to transform the current array:
...
const contnumArray = rows.map(r => r.countnum)
var string = json.stringify(countnumArray)
...
Also, why do you stringify parse your array ? You should just send it...
You may have a look at Node.js MySQL Select From to know more about managing MySQL requests using node.js.