Node.js如何在页面上显示多个类别的文章

时间:2018-01-15 04:57:44

标签: javascript node.js express mongoose

我想限制每个类别可以使用.limit()函数显示的帖子数量,我不知道如何通过这个来实现。

我正在使用Mongoose和Express。

到目前为止,我的代码如下。

router.get('/', function (req, res) {
  MainArticle.find({ category: ['Worldwide', 'U.S. News'] },  function (err, mainArticles) {
    if (err) {
      console.log(err);
    } else {
      res.render('landing', { mainArticles: mainArticles });
    }
  });
});

如果我要用EJS输出结果,它将显示两个类别的所有结果。如果我要限制,它只会限制我设置的整数。

我不知道该传递什么,所以我可以在网页的不同部分显示这两篇文章,并限制显示的帖子数量。

router.get('/profile', function (req, res) {
  // Retrieve the desired count for each category (for example, through a query parameter) defaulting to some number as needed.
  var limit = req.query.limit || 10;

  // Create an object to hold the results
  var result = {};

  // Get data for the world wide category
  MainArticle.find({
      category: ['Worldwide'],
    })
    .limit(limit)
    .exec(function (err, worldwideArticles) {
      if (err) {
        console.log(err);
      } else {
        // Add the worldwide data to the result set
        result.worldwideArticles = worldwideArticles;

        // Get data for the US news category
        MainArticle.find({
            category: ['U.S. News'],
          })
          .limit(limit)
          .exec(function (err, usArticles) {
            if (err) {
              console.log(err);
            } else {
              result.usArticles = usArticles;

              // Hand the two different sets separately to the template
              // You will obviously have to change the template code to handle the new data structure of different categories
              res.render('profile', { result: result });
            }
          });
      }
    });
});

EJS

<script type="text/javascript">
   var json_data = <%= JSON.stringify( result ); %>
</script>

此处显示“全球”的文章,限于10篇文章。

  <ul>
    <% result.worldwideArticles.forEach(function(mainArticles){ %>
    <li>
      <div class="img-container">
          <a href="/articles/<%= mainArticles._id %>"><img src="<%= mainArticles.image %>" alt=""></a>
           <div class="title-container">
            <a href="/articles/<%= mainArticles._id %>"><%=mainArticles.title %></a>
          </div>
      </div>
     <% }); %>

3 个答案:

答案 0 :(得分:2)

你可以看看我会在这里做些什么。如果有效,请告诉我。

router.get('/', (req, res) => {
  MainArticle
    .where('category')
    .in(['Worldwide', 'U.S. News'])
    .limit(10)
      .then(mainArticles => {
        res.render('landing', { mainArticles })
      })
      .catch(err => {
        console.log(err)
      })
  )
}

可能需要在这里选择,但我无法测试它。如果它不起作用,只需在.in后添加要选择的属性。比如.select('name', 'age', 'tags')甚至更好.select({})但是我不知道没有测试会有什么效果。我刚刚在这里找到文档:

http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html

阅读查询API另一种方法是这样的:

router.get('/', (req, res) => {
  const fetchArticles = MainArticle.find({})

  fetchArticles
    .where('category')
    .in(['Worldwide', 'U.S. News'])
    .limit(10)
      .then(mainArticles => {
        res.render('landing', { mainArticles })
      })
      .catch(err => {
        console.log(err)
      })
  )
}

..或者如果你想得到幻想:

router.get('/', async (req, res) => {

    function getArticles() {
        return MainArticle
            .where('category')
            .in(['Worldwide', 'U.S. News'])
            .limit(10)
            .exec()
    }

    try {
        let mainArticles = await getArticles()
        res.render('landing', { mainArticles })
    } catch (error) {
        console.log(error)
    }
}

根据您上一次提交更新。

  router.get('/', async (req, res) => {

    function getWorldwideArticles() {
        return worldwideArticles
            .where('category')
            .in(['Worldwide'])
            .limit(10)
            .exec()
    }

    function getUSArticles() {
      return usArticles
          .where('category')
          .in(['U.S. News'])
          .limit(10)
          .exec()
    }

    try {
        let worldwideArticles = await getWorldwideArticles()
        let usArticles = await getUSArticles()
        res.render('landing', { worldwideArticles, usArticles })
    } catch (error) {
        console.log(error)
    }
  }

答案 1 :(得分:1)

我通过使用Chirag Ravindra发布和传递的内容解决了这个问题

<script type="text/javascript">
     var json_data = <%- JSON.stringify( result ); %>
 </script>

在我的EJS上的forEach语句之上,因为EJS can't call variables from clientside

然后我刚用

<% result.worldwideArticles.forEach(function(mainArticles){ %>
<% }); %>

<% result.usArticles.forEach(function(mainArticles){ %>
<% }); %>

我想发布这两个类别。

答案 2 :(得分:0)

执行此操作的一种方法是单独查询每个类别,并通过在结果中的不同键上设置两个find操作的结果来为模板构建结果。

&#13;
&#13;
router.get('/', function(req, res) {
  // Retrieve the desired count for each category (for example, through a query parameter) defaulting to some number as needed.
  var limit = req.query.limit || 10;

  // Create an object to hold the results
  var result = {};
  // Get data for the world wide category
  MainArticle.find({
      category: ['Worldwide']
    })
    .limit(limit)
    .exec(function(err, worldwideArticles) {
      if (err) {
        console.log(err);
      } else {
        // Add the worldwide data to the result set
        result.worldwideArticles = worldwideArticles;
        // Get data for the US news category
        MainArticle.find({
            category: ['U.S. News']
          })
          .limit(limit)
          .exec(function(err, usArticles) {
            if (err) {
              console.log(err);
            } else {
              result.usArticles = usArticles;
              // Hand the two different sets separately to the template
              // You will obviously have to change the template code to handle the new data structure of different categories
              res.render('landing', result);

            }
          });
      }
    });
});
&#13;
&#13;
&#13;