Raz*_*fir 3 javascript ejs node.js express mean-stack
我正在使用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);
};
Run Code Online (Sandbox Code Playgroud)
视图中的寻呼机:
<% 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>
<% } %>
Run Code Online (Sandbox Code Playgroud)
.limit(perPage)来自控制器的行在perPage is not defined控制台 (Git bash) 中给出了错误。
显然,我可以将这两行移到上面 const posts
const perPage = 5;
const currPage = req.query.page ? parseInt(req.query.page) : 1;
Run Code Online (Sandbox Code Playgroud)
但我不能这样做const postsCount = posts.length;(我在视图中也需要)。
我正在尝试使有关分页的代码片段可重用(如果可能,就像插件一样),因为我需要为按类别过滤的帖子以及应用程序管理部分中的帖子列表进行分页。
我究竟做错了什么?
为什么你一起使用回调和等待。似乎你需要查看异步/等待和承诺。你可以做的如下:
exports.getPosts = async (req, res, next) => {
const currPage = req.query.page ? parseInt(req.query.page) : 1;
const perPage = 10;
try {
const posts = await Post.find({})
.sort({ created_at: -1 })
.populate("category")
.limit(perPage)
.skip((currPage - 1) * perPage).exec();
const postsCount = posts.length;
const pageCount = Math.ceil(postsCount / perPage);
const pageDecrement = currPage > 1 ? 1 : 0;
const pageIncrement = currPage < pageCount ? 1 : 0;
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,
});
} catch (err) {
console.log("Error: ", err);
// add proper error handling here
res.render('default/error', {
err
});
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
525 次 |
| 最近记录: |