使用Sequelize与Handlebars无法展示用户文章标题的问题求助
问题描述
我是编程新手,正在开发一款支持用户撰写并发布文章的基础网站。在用户账户页面,我需要展示该用户的文章历史,但使用Sequelize和Handlebars时,页面能正常显示用户名,却无法在历史板块展示文章标题。
控制器代码:
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 }) }
Handlebars页面代码:
<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}} </div>
控制台中直接访问stories.title显示undefined,但通过forEach循环遍历stories却能获取到文章标题值,对此我感到困惑,希望能得到解决方案。
解决方案
问题核心是Sequelize返回的stories是模型实例数组,而非普通JSON对象,Handlebars无法直接识别实例的属性访问器。
具体修复方法:
- 查询时直接返回纯JSON
在Story.findAll中添加raw: true选项,让Sequelize跳过模型实例包装,直接返回数据库原始数据:
const stories = await Story.findAll({ where: { userId: user.id }, raw: true // 新增配置 })
- 手动转换实例为JSON
如果需要保留模型实例的其他功能,可以在查询后用toJSON()方法转换每个实例:
const storyInstances = await Story.findAll({ where: { userId: user.id } }) const stories = storyInstances.map(story => story.toJSON())
- 验证字段匹配
确认Handlebars中的{{title}}和Story模型定义的字段名完全一致,比如模型里如果是storyTitle,模板里也要对应修改。
控制台现象解释:
stories.title是访问数组本身的属性,数组没有title字段,所以返回undefined;forEach遍历的是数组内的每个模型实例,实例通过内置的getter方法可以读取title属性,因此能正常打印值。
内容的提问来源于stack exchange,提问作者CooperPeaks
相关产品推荐
相关产品推荐

