Node js中的变量范围,从MongoDB中检索数据

时间:2017-07-15 11:09:23

标签: javascript node.js mongodb

我遇到了一个问题,我无法弄清楚如何以一种简单的方式解决它,我已经了解了变量范围在Node js中是如何工作的,但我认为有一种简单的方法可以解决我的问题问题,我无法看到。

这里我正在检索来自MongoDB的帖子,我必须提取标题,以便在HTML页面中创建一个" div"对于每个帖子,为了做到这一点,我使用ejs,我必须将我的内容传递给它。 (我知道我也可以传递一系列标题并在.ejs文件中移动html代码以获得更优雅的代码)

但是muy问题是另一个问题, 我用" var htmlposts"用于存储我从数据库中获取的标题,但是在posts.each(...)方法中声明的变量在该函数内部是不可见的,我实际上无法理解如何在该方法中实例化该变量。 (我无法在id中移动变量,否则我无法在需要它的地方调用它,即在res.render()方法中,我无法调用res.render函数posts.each()内部的()方法,因为它将为集合帖子中的每个元素调用。)

请帮忙

// 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
      });
    });
});

0 个答案:

没有答案
相关问题