Question

I am trying to display data from my mongodb backend to an hbs template by trying to port over this tutorial. I do not get any errors from the server logs or the console in the browser, but I do not get any data represented on the template. Interestingly enough, however, it is generating html markup. Please help me see the issue.

*Note using express framework (and still learning)

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 template:

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

Thanks in advance!

Was it helpful?

Solution

I assume you are using the mongodb driver,which you did not specify.

collection.find returns a mongodb cursor , not an array of documents. You can use toArray to get the documents :

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

I suggest your read the documentation of the library before using it,because you just can guess what an api does.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top