我正在研究一个博客应用程序 https://github.com/Ajax30/XPressBlog(点击链接即可查看GitHub回购)与Express https://expressjs.com/, EJS https://ejs.co/和 MongoDB。
我为帖子制作了一个简单的寻呼机。
在帖子中控制器 I have:
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)
从控制器给出错误perPage is not defined
在控制台(Git bash)中。
不起作用的解决方案
显然,我可以将这两行移到上面const posts
const perPage = 5;
const currPage = req.query.page ? parseInt(req.query.page) : 1;
但是我可以not做同样的事情const postsCount = posts.length;
(我在视图中也需要)。
目标
我正在尝试制作有关分页的代码片段reusable(就像一个插件,如果可能的话),因为我需要对按类别过滤的帖子以及应用程序管理部分中的帖子列表进行分页。
我究竟做错了什么?