【问题标题】:Cannot access object property from an array in Handlebars无法从 Handlebars 中的数组访问对象属性
【发布时间】:2020-05-04 11:49:45
【问题描述】:

即使在查看how-to-iterate-over-array-of-objects-in-handlebars 之后,我也无法让它工作。我正在使用猫鼬模型,并且想简单地迭代对象并显示标题和详细信息:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const IdeaSchema = new Schema({
title: {
    type: String,
    required: true
},
details: {
    type: String,
    required: true
},
date: {
    type: Date,
    default: Date.now
}
});

mongoose.model('ideas', IdeaSchema);

这是我的车把模板:

{{#each ideas}}
        <div class="card card-body">
            <h4>{{title}}</h4>
            <p>{{details}}</p>      
        </div>
{{/each}}

它显示 2 个空 div,里面没有内容:

<div class="card card-body">
    <h4></h4>
    <p></p>      
</div>
<div class="card card-body">
    <h4></h4>
    <p></p>      
</div>

这是加载集合的代码

Idea.find({})
    .sort({ date: 'desc' })
    .then(ideas => {
        res.render('ideas/index', {
            ideas: ideas
        });
});

【问题讨论】:

    标签: node.js express mongoose handlebars.js express-handlebars


    【解决方案1】:

    您没有在填充变量ideas 并设置把手的位置提供代码 sn-p。请提供,或者如果您没有提供,请从以下开始:

    您需要分配并可能导出(如果在不同的模块中使用)Mongoose 正在为您编译的模型:

    export const IdeaModel = mongoose.model('ideas', IdeaSchema);
    

    然后使用它来填充变量ideas,例如:

    const ideas = IdeaModel.find({}); // fetch all ideas or add query criteria
    

    然后将ideas 传递给车把template 函数,如:

    const html = template({ ideas });
    

    【讨论】:

    • 这是您要求的代码:Idea.find({}) .sort({ date: 'desc' }) .then(ideas =&gt; { res.render('ideas/index', { ideas: ideas }); });
    • 检查查询是否正在使用 console.log 或调试器返回数据。如果是,您需要查阅文档以了解您正在使用的任何快速中间件和/或发布设置中间件的代码。
    【解决方案2】:

    我通过安装车把的开发依赖项解决了这个问题。详情见https://stackoverflow.com/a/59704492/3141885

    【讨论】:

      【解决方案3】:

      提供的代码可以解决

      dbName.find({}).lean().then((ideas) => {
       res.render('ideas/index', { ideas: ideas });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        • 2021-08-23
        • 2017-09-04
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 2014-03-10
        相关资源
        最近更新 更多