I am working on a blogging application (click the link to see the GitHub repo) with Express, EJS and MongoDB.
Trying to paginate the posts I got stuck with passing newerPosts
and olderPosts
to the view. I am passing them just like the posts
variable (and other variables):
exports.getPosts = async (req, res, next) => {
//pagination params
var perPage = 10;
var currPage = req.body.page ? parseInt(req.body.page) : 1;
const newerPosts = function() {
currPage = currPage + 1;
console.log(currPage);
}
const olderPosts = function() {
currPage = currPage - 1;
console.log(currPage);
}
const posts = await Post.find({}, (err, posts) => {
if (err) {
console.log('Error: ', err);
} else {
res.render('default/index', {
moment: moment,
layout: 'default/layout',
website_name: 'MEAN Blog',
page_heading: 'XPress News',
page_subheading: 'A MEAN Stack Blogging Application',
posts: posts,
newerPosts: newerPosts,
olderPosts: olderPosts
});
}
})
.sort({
created_at: -1
})
.skip((currPage - 1) * perPage)
.limit(perPage)
.populate('category');
};
In the view:
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="olderPosts()"%>>← Older Posts</a>
</div>
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="newerPosts()"%>>Newer Posts →</a>
</div>
Yet, I get the Uncaught ReferenceError: newerPosts is not defined
error message from the browser.
What am I doing wrong? What is the closest working alternative?