服务器端代码(article.js)
通过引入mongoose-sex-page的方式处理文章页面分页
下面是引入方式和获得的方法返回数据。
//将用户集合构造模板导入
const { Article } = require('../../model/article');
//导入数据库分页第三方模块
const pagination = require('mongoose-sex-page');
module.exports =async (req, res) => {
//给服务器一个属性值用于客户段判断当前显示在用户还是文章
req.app.locals.currentLink = 'article';
//接收服务器传过来的page参数
const page = req.query.page;
//查找所有用户 .populate多集合联合查询(里边是查询的字段信息,
//本例子中author存储_id信息,因为我们表单中默认填的,联合查到_id的详细信息())
//Pagination接收文章模板作为参数,.find查找所有用户
//.page是分页里边page参数保存客户端传来的当前页码;size是每页显示多少条;
//disply是客户端显示页码(注意不是页码总数,页码总数是根据.find查询出的总数除以每页显示数据)
//不要忘了.exec是查询数据,否则不会显示
const articles = await pagination(Article).find().page(page).size(2).display(3).exec();
//将模板渲染给用户界面
res.render('admin/article', {
articles:articles
});
}
客户端代码(article.art)
要注意服务器传递过来的articles不再是之前的从数据库查询出的数据,而是一个对象(数据分页),其中articles.records得到的才是查询出的文章数据
<!-- 内容列表 -->
<table class="table table-striped table-bordered table-hover custom-table">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
<th>发布时间</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<!-- records里边才是实际查询出来的用户信息 -->
{{each articles.records}}
<tr>
<td>{{@$value._id}}</td>
<td>{{$value.title}}</td>
<td>{{dateFormat($value.publishDate,'yyyy-mm-dd')}}</td>
<td>{{$value.author}}</td>
<td>
<a href="article-edit.html" class="glyphicon glyphicon-edit"></a>
<i class="glyphicon glyphicon-remove" data-toggle="modal" data-target=".confirm-modal"></i>
</td>
</tr>
{{/each}}
</tbody>
</table>
<!-- /内容列表 -->
<!-- 分页 -->
<ul class="pagination">
<!-- 如果当前页大于1 显示< -->
{{if articles.page > 1}}
<li>
<a href="/admin/article?page={{$value-1}}">
<span>«</span>
</a>
</li>
{{/if}}
<!-- display保存页码总数,循环 -->
{{each articles.display}}
<!-- 将页码作为参数传入服务器 -->
<li><a href="/admin/article?page={{$value}}">{{$value}}</a></li>
{{/each}}
<!-- 如果当前页小于总页数,显示> -->
{{if articles.page < articles.pages}}
<li>
<a href="/admin/article?page={{$value-0+1}}">
<span>»</span>
</a>
</li>
{{/if}}
</ul>
<!-- /分页 -->