I want to limit how many posts each category can display with a .limit() function and i am not sure how to come by this.
I am using Mongoose and Express.
My code so far is a follows.
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 });
}
});
});
If i was to output the results with EJS, it will display all the results of both categories. And if i was to limit, it would just limit to the integer i set.
I'm not sure what to pass on so i can display the two articles at different parts of the webpage as well as limit how many posts to show.
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>
This displays articles for "Worldwide", limited to 10 articles.
<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>
<% }); %>