Reputation: 1256
I was trying to return a JSON Object but instead it returns an array. I am using primary key for query so I am sure I will only get one result.
This is my approach :
router.get("/student_info/:id", (req, res, next) => {
connection.getConnection((error, currentConnection) => {
if (!!error) {
console.log("Error occurred while connecting db")
} else {
let id = req.params.id;
currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
if (!!error) {
console.log(error.message)
} else {
res.status(200).json(rows);
}
currentConnection.release();
});
}
});
});
What I want is this :
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
But I get the result like this :
[
{
"id": "171-15-8966",
"name": "Alif Hasnain",
"course_code": "CSE412,CSE413"
}
]
Upvotes: 1
Views: 1832
Reputation: 684
Try this, using nested array destructuring
res.status(200).json([[rows]]);
You can read this blog to learn more about ES6 - Destructuring
ES6 - Understanding Destructuring
Upvotes: 0
Reputation: 144
By default query return the array of rows reflected by the select query. Since your query has single result it returns as array of single object to user.
You can change it to
res.status(200).json(rows[0]);
Please let us know if got better alternate.
Upvotes: 1
Reputation: 222482
Just get the first element of the array before the json transformation:
res.status(200).json(rows[0]);
Upvotes: 1