0

I am stacked with a problem and I can't figure out how to solve it in a simple way, I have looked around how variable scopes work in Node js but still I think there is an easy way to solve my problem and I can't see that.

Here I am retrievering posts from a MongoDB, and I have to extract the title in order to create in the HTML page a "div" for each post, for doing that I'm using ejs and I have to pass my content to it. (I know I can also pass an array of titles and move the html code in the .ejs file for a more elegant code)

But muy problem is another, I use "var htmlposts" for storing the titles that I get from the database, but the variable declared out of the posts.each(...) method is not visible inside that function and I really can't understand how to instantiate that variable inside that method. (I can't move the variable inside id, otherwise I wouldn't be able to call it where I need it, i.e, in the res.render() method, and I cannot either call the res.render() method inside the function posts.each() because it would be called for each element in the collection posts).

Please help

// post page
app.get('/posts', function(req, res) {

   MongoClient.connect(url, function(err, db) {

   if (err) throw err;

      //Find each single element
      var posts = db.collection("posts").find();
      var htmlposts;

      //For each element extract the title and body
      posts.each(function(err, docs, callback){
        if (docs != null){
          console.log("The title is: " + docs.title);
          console.log("The text is: " + docs.body);
          htmlposts = "<div class=\"row\"><div class=\"col-1\"> \
          <button>CHAT NOW</button></div><div class=\"col-8\">" + docs.title + "</div> \
          <div class=\"col-2\">Statistics</div></div>";
        }
      });

      db.close();
      //This will print undefined, and that's the problem
      console.log(htmlposts);
      res.render('pages/posts', {
        page_name: 'posts',
        page_title: 'All Posts | ChatWhatHappened',
        page_posts: htmlposts
      });
    });
});
AleDG
  • 84
  • 6
  • Use htmlposts += to concat the content – Jonas Wilms Jul 15 '17 at 11:17
  • Don't connect and close database connections within the scope of a request. Instead persist the connection through the life-cycle of your application. But mostly, learn how to use "async" functions properly. Calls to the database are "async" and do not return values in this context. – Neil Lunn Jul 15 '17 at 11:19

0 Answers0