You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Handlebars模板引擎循环数据渲染异常问题求助

解决方案

1. 转换MongoDB文档为普通JavaScript对象

MongoDB查询返回的是Mongoose文档对象,而非纯JS对象,Handlebars无法直接识别其内部属性。解决方法如下:

  • 用.lean()直接获取纯JS对象数组:
    // 后端查询代码修改
    const userArray = await userReg.find({}).lean();
    res.render('你的模板文件名', { userArray });
    
  • 手动遍历转换:如果无法使用.lean(),可以逐个将文档转为对象:
    const docs = await userReg.find({});
    const userArray = docs.map(doc => doc.toObject());
    res.render('你的模板文件名', { userArray });
    

2. 修正Handlebars模板的字段访问写法

确保模板内直接访问单个用户文档的属性,字段名要和MongoDB文档的字段完全一致(注意大小写):

{{#each userArray}}
  <div class="user-item">
    ID: {{_id}}<br>
    姓名: {{name}}<br>
    邮箱: {{email}}
  </div>
{{/each}}

不需要用{{#each userArray.[0]}}这种冗余写法,{{#each userArray}}循环内部直接访问属性即可。

3. 验证传递给模板的数据结构

在后端res.render之前,打印数据结构确认是否为普通对象数组:

console.log(JSON.stringify(userArray, null, 2));

如果输出中字段嵌套在_doc属性下(比如_doc.name),说明是Mongoose文档未转换,必须用上述第1种方法处理。

内容的提问来源于stack exchange,提问作者Vidhu Prakash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:02:32