Issue
I am developing a handlebars app,
router.get('/findBehavior/:student_id', async (req, res) => {
console.log("---> req.params.student_id :" + JSON.stringify(req.params.student_id));
const student = await Student.findByPk(req.params.student_id,{
include: Behavior,
});
console.log("---> student :" + JSON.stringify(student));
res.render('profile', {student, session: req.session});
});
but I have trouble reading this json data that comes into the profile.handlebars:
{
"student_id": 1,
"student_name": "Martina Hodson",
"student_grade": 9,
"Behaviors": [
{
"behavior_id": 1,
"behavior_name": "No Problems",
"StudentBehavior": {
"student_id": 1,
"behavior_id": 1
}
}
]
}
I am trying this code, but it is not working…
{{student.Behaviors.[0].['behavior_id']}}
I get a response of
[object SequelizeInstance:Behavior]
How can I get the student’s name and the student’s behaviors?
Solution
The problem was not the way I was trying to read the JSON.
It was that the object that comes in response of the search needs to be ‘cleaned’ before being passed to the handlebars page.
I used this code to make the object plain:
const student = dbStudentData.get({plain: true});
Yo can see how it appears surrounded by the rest of the code:
router.get('/findBehavior/:student_id', async (req, res) => {
console.log("---> req.params.student_id :" + JSON.stringify(req.params.student_id));
const dbStudentData = await Student.findByPk(req.params.student_id, {
include: Behavior,
});
// HERE --------------------------------------------------------
const student = dbStudentData.get({plain: true});
console.log("---> student :" + JSON.stringify(student));
res.render('profile', {student, session: req.session});
});
Since it was only one row of data, It wasn’t needed a map function to make plain whole set of data when there is more than one row.
Answered By – Gianni Fontanot
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0