【发布时间】:2018-01-15 04:57:43
【问题描述】:
我想通过 .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>
<% }); %>
【问题讨论】:
-
查看
filter。.find将返回第一个匹配对象或 null -
澄清一下,您希望将
'Worldwide'和'U.S News'设置在不同的键上,以便您的目标网页? -
是的,没错。
标签: javascript node.js express mongoose