我正在开发一个使用Express、EJS和MongoDB的博客应用程序(点击链接查看GitHub存储库)。
我已经为文章制作了一个简单的分页器。
在文章控制器中,我有:
视图中的寻呼机:
问题:
但我无法像处理
我已经为文章制作了一个简单的分页器。
在文章控制器中,我有:
exports.getPosts = async (req, res, next) => {
const posts = await Post.find({}, (err, posts) => {
const perPage = 10;
const currPage = req.query.page ? parseInt(req.query.page) : 1;
const postsCount = posts.length;
const pageCount = Math.ceil(postsCount / perPage);
const pageDecrement = currPage > 1 ? 1 : 0;
const pageIncrement = currPage < pageCount ? 1 : 0;
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",
currPage: currPage,
pageDecrement: pageDecrement,
pageIncrement: pageIncrement,
posts: posts,
});
}
})
.sort({ created_at: -1 })
.populate("category")
.limit(perPage)
.skip((currPage - 1) * perPage);
};
视图中的寻呼机:
<% if (posts) {%>
<div class="clearfix d-flex justify-content-center">
<div class="px-1">
<a class="btn btn-primary <%= pageDecrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage - pageDecrement %>">← Newer Posts</a>
</div>
<div class="px-1">
<a class="btn btn-primary <%= pageIncrement == 0 ? 'disabled' : '' %>" href="/?page=<%= currPage + pageIncrement %>">Older Posts →</a>
</div>
</div>
<% } %>
问题:
问题
控制器中的代码行.limit(perPage)
在控制台(Git bash)中报错perPage未定义
。
无效的解决方案
显然,我可以将这两行移到const posts
上面
const perPage = 5;
const currPage = req.query.page ? parseInt(req.query.page) : 1;
但我无法像处理
const postsCount = posts.length;
那样在视图中重复使用(这也是我需要的)。
目标
我试图将分页代码片段做成可重用的(如果可能的话,像插件一样),因为我需要对按类别过滤的帖子进行分页,并且还需在应用程序的管理员部分中对帖子列表进行分页。
我做错了什么?
perPage
变量是正确的作用域。在const posts
之前尝试定义它。 - Denis Lapadatovic