读mongodb到HBS(车把)模板

时间:2014-03-27 00:07:04

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

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

*注意使用快速框架(并且还在学习)

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}}

提前致谢!

1 个答案:

答案 0 :(得分:1)

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

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

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

我建议您在使用之前阅读该库的文档,因为您可以猜出api的作用。

相关问题