'MySQL returning Object of RowDataPacket to node js express
I am trying to select items from the DB but every time i call the select statment SQL returns an RowDataPacket object and i cant seem to find a way to access that object. What i am trying to do is to call that object from ejs file.
this is my ejs file
<%- include('../partials/header', {title:title}) %>
<body>
<%- include("../partials/nav", {title: title}) %>
<div class="contaienr">
<p><% console.log(Object.values(JSON.parse(JSON.stringify(res)))[0]) %> </p>
<img src="<%= res.bild %> ">
<h2><%= res.namn %> </h2>
<p><%= res.beskrivning %> </p>
<form action="">
<button></button>
<input type="number" name="" id="" min="1" max="<%= res.antal %> ">
</form>
</div>
<%- include("../partials/footer", {title: title}) %>
</body>
</html>
This is the function that gets the data
async function getProduct(id)
{
let sql = `CALL get_product(?)`;
let res;
res = await db.query(sql, [id]);
console.log(res);
return res;
}
and this is the function that displays the page
router.get("/product/:id", async (req, res) =>
{
let id = req.params.id;
let data = {
title : `Product ${id} | BuckStar`,
product : id
}
data.res = results.getProduct(id);
res.render("pages/product", data);
});
this is the output in the console
undefined
[
[
RowDataPacket {
kod: 1111,
kategori: 'Arabica',
namn: 'Coffe 1',
beskrivning: 'I am a coffe',
pris: 100,
antal: 0,
plats: '1A',
bild: '1'
}
],
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
]
Solution 1:[1]
I have had similar problems. Using my own database with a Customers table I can call an SP to get details for a specified customer, in this case with ID = 3:
let sql_custDetails = `call sp_GetCustomerInfo(?)`
connection.query(sql_custDetails, 3, (error, result, fields) => {
if (error) {
return console.error(error.message);
}
console.log(result[0][0].GivenName); //THIS works
});
If I log the full result to the console I get:
[
[
RowDataPacket {
GivenName: 'Santa',
FamilyName: 'Claus',
Phone: '11111',
Email: '[email protected]',
AccountNumber: 'A-22-0003',
LastVisit: 2022-03-30T23:00:00.000Z
}
],
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
]
But simply using:
console.log(result[0][0].GivenName);
I get:
Santa
which is the correct answer!
Don't ask me about why [0][0] is correct, as I have no idea.
I hope that helps in some small way,
Dermot
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DermotMW |
