【问题标题】:Reading mongodb to HBS (handlebars) template读取 mongodb 到 HBS(车把)模板
【发布时间】:2014-03-27 00:07:04
【问题描述】:

我试图通过移植this 教程将数据从我的 mongodb 后端显示到 hbs 模板。我没有从服务器日志或浏览器中的控制台中得到任何错误,但我没有得到模板上表示的任何数据。然而,有趣的是,它正在生成 html 标记。请帮我看看问题。

*注意使用 express 框架(还在学习中)

app.js:

app.post("/", function(req, res){
     res.render("default", {title:"posts", entries:myRoute.getBlogEntries()});
});

myRoute.js:

exports.getBlogEntries = function(res) {
mongo.connect("mongodb://localhost:27017/myDB", function(err, db){
       if(err) { return console.dir(err); }

       var collection = db.collection("posts");
       collection.find({},{},function(e,docs){
                   res.render("default", {
                       "entries" : docs
               });
         });
});
};

hbs 模板:

{{#each entries}}
<form method="POST">
  <div class="well">
    <div class="row">
      <div class="col-md-1">
        <div>
          <button type="submit" value="{{_id}}" class="btn btn-lrg btn-primary" name="voteup" title="Vote post up"><span class="glyphicon glyphicon-thumbs-up"></span></button>
        </div>
        <div style="text-align:center;padding-right:5px;padding-top:7px;padding-bottom:7px;"><span class="badge">{{voteCount}}</span></div>
        <div>
          <button type="submit" value="{{_id}}" class="btn btn-lrg btn-danger" name="votedown" title="Vote post down"><span class="glyphicon glyphicon-thumbs-down"></span></button>
        </div>
      </div>
      <div class="col-md-10">
          <h4>{{title}}</h4>
          <label style="font-weight:normal;font-style:italic">Posted: {{published}}</label>
          <div>
            {{body}}
          </div>
      </div>
    </div>
  </div>
</form>
{{/each}}

提前致谢!

【问题讨论】:

    标签: node.js mongodb express handlebars.js template-engine


    【解决方案1】:

    我假设您使用的是您未指定的 mongodb 驱动程序。

    collection.find 返回一个 mongodb 游标,而不是一个文档数组。您可以使用 toArray 来获取文档:

    collection.find().toArray(function(e,docs){
       ...
    }
    

    我建议你在使用它之前阅读该库的文档,因为你可以猜测一个 api 的作用。

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      相关资源
      最近更新 更多