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

Handlebars #each助手迭代异常,无法正确读取MongoDB数组字段

Handlebars迭代MongoDB数组无法正确取值的问题解决

问题重现

Handlebars模板代码

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Message</th>
      <th scope="col">Time</th>
    </tr>
  </thead>
  <tbody>
    {{#each result}}
    <tr>
      <th scope="row">{{@index}}</th>
      <td>{{this.name}}</td>
    </tr>
    {{/each}}
  </tbody>
</table>

MongoDB返回的数据结构

[
  {
    _id: new ObjectId("651de76a44d50f1d9cfedede"),
    name: 'Lucy',
    message: 'I way',
    createdAt: 2023-10-04T22:30:02.377Z,
    updatedAt: 2023-10-04T22:30:02.377Z,
    __v: 0
  },
  {
    _id: new ObjectId("651de7eca2da2627f94ce3cb"),
    name: 'Tanya',
    message: 'I like chemical',
    createdAt: 2023-10-04T22:32:12.465Z,
    updatedAt: 2023-10-04T22:32:12.465Z,
    __v: 0
  },
  {
    _id: new ObjectId("651de8854ee4b125468e6921"),
    name: 'Otto',
    message: 'I from hightower',
    createdAt: 2023-10-04T22:34:45.179Z,
    updatedAt: 2023-10-04T22:34:45.179Z,
    __v: 0
  }
]

异常现象

  • 使用{{this}}时,能正常输出完整的对象内容;
  • 使用{{name}}或{{this.name}}时,无法显示对应字段值,输出为空。

解决方法

1. 将Mongoose文档转为普通JavaScript对象

MongoDB通过Mongoose查询返回的是Mongoose文档对象,而非原生JS对象,这类对象的属性访问受Mongoose封装影响,导致Handlebars无法直接读取。解决方式是在查询时添加.lean()方法:

// 修改前查询(返回Mongoose文档)
// const result = await YourModel.find();

// 修改后查询(返回普通JS对象)
const result = await YourModel.find().lean();

转换后,Handlebars就能正常通过{{name}}或{{this.name}}访问属性。

2. 验证模板上下文

在模板中添加日志输出,确认result的结构和属性是否正确传递:

{{log result}} {{! 在浏览器控制台查看result的实际结构 }}
{{#each result}}
  {{log this}} {{! 查看当前迭代对象的具体内容 }}
  <tr>
    <th scope="row">{{@index}}</th>
    <td>{{name}}</td>
  </tr>
{{/each}}

通过控制台日志确认每个对象的name属性是否存在、拼写是否正确。

3. 检查字段名一致性

确认MongoDB集合中的字段名与模板中使用的name完全一致,避免大小写错误(如Name)或拼写失误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:02:50