Skip to content

Instantly share code, notes, and snippets.

@dzt
Created May 15, 2019 05:03
Show Gist options
  • Save dzt/92f568bfdf4cb61c55c67e4642d7125c to your computer and use it in GitHub Desktop.
Save dzt/92f568bfdf4cb61c55c67e4642d7125c to your computer and use it in GitHub Desktop.
Pagination using MongoDB, Nunjucks, and Express
<small class="d-block text-right mt-3" style="padding-top: 30px;padding-bottom: 30px;">
{% set current = current|int %}
{% set pages = pages|int %}
{% if pages > 0 %}
<ul class="pagination text-center" style="position: absolute;left:50%;transform: translate(-50%,-50%);">
{% if current == 1 %}
<li class="page-item disabled"><a class="page-link">First</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="/admin/bundles/1">First</a></li>
{% endif %}
{% if current > 5 %}
{% set i = current - 4 %}
{% else %}
{% set i = 1 %}
{% endif %}
{% if i !== 1 %}
<li class="page-item disabled"><a class="page-link">...</a></li>
{% endif %}
{% set length = current + 4 %}
{% for x in range(i, length) %}
{% if x <= pages %}
{% if x == current %}
<li class="page-item active"><a class="page-link">{{ x }}</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="/admin/bundles/{{ x }}">{{ x }}</a></li>
{% endif %}
{% if (x == current + 4) and (x < pages) %}
<li class="disabled page-item"><a class="page-link">...</a></li>
{% endif %}
{% endif %}
{% endfor %}
{% if current == pages %}
<li class="disabled page-item"><a class="page-link">Last</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="/admin/bundles/{{ pages }}">Last</a></li>
{% endif %}
</ul>
{% endif %}
</small>
router.get('/bundles/:page', isAdmin, (req, res) => {
let perPage = 2
let page = req.params.page || 1
discord.getRoles(settings.discord.bot_token, settings.discord.guild_id, async (err, roles) => {
let rolesArr = roles.map(x => {
x.color = intToRGB(x.color);
return x;
});
Bundle
.find({})
.skip((perPage * page) - perPage)
.limit(perPage)
.exec((err, bundles) => {
Bundle.count().exec((err, count) => {
if (err) return next(err);
return res.render('admin/bundles', {
bundles: bundles,
roles: _.reject(rolesArr, (x) => {
return x.name == '@everyone' || x.managed;
}),
current: page,
pages: Math.ceil(count / perPage),
page: 'bundles',
max: Math.max
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment