I'm a beginner in programming and I'm currently working on a website project : a basic one where the user can write and post articles. On the user account page, I want to display the history of articles written by the user. For this, I'm using sequelize and handlebars, but the problem is that my page display the username, but not the article's title in the History Section. So I was wondering if you got some solutions for my problem.
In my controller, I take reference from my User and Story models to get only the stories written by the current user. Then I make a res.render of my variables to use them in my hbs page : My controller :
getAccount: async (req, res) => {
const user = await User.findOne({where: {username: req.session.username}})
const stories = await Story.findAll({
where: {
userId: user.id
}
})
console.log(stories, stories.title);
stories.forEach(story => {console.log(story.title);})
res.render('user_account', { user, stories })
}
My page :
<div class="user-title">
<h1>Hello {{username}} </h1>
</div>
<div class="storyList-pannel">
<h2>History</h2>
<div class="articles-pannel">
{{#each stories}}
<div class="article-title">
<h3> {{title}} </h3>
</div>
{{/each}}
In my console, I see that the title is undefined but I still can get it value when I make a forEach loop on my variable, which I don't really understand why.
You should try passing the raw: true
option to the query. As per the Model Querying docs:
By default, the results of all finder methods are instances of the model class (as opposed to being just plain JavaScript objects). This means that after the database returns the results, Sequelize automatically wraps everything in proper instance objects. To disable this wrapping and receive a plain response instead, pass { raw: true } as an option to the finder method.
It is well documented that, by default, in Handlebars >= v4.6.0 accessing prototype properties and methods of the context object is forbidden by the runtime. By getting a raw query returned by sequelize your handlebars templates will be access the object properties.
Pass like so:
const stories = await Story.findAll({
where: {
userId: user.id
},
raw: true
});