Skip to content

Instantly share code, notes, and snippets.

@Faizanq
Created January 9, 2019 16:46
Show Gist options
  • Select an option

  • Save Faizanq/a4d07f1a9624bdf6d3ddd9d4d6cc1b2d to your computer and use it in GitHub Desktop.

Select an option

Save Faizanq/a4d07f1a9624bdf6d3ddd9d4d6cc1b2d to your computer and use it in GitHub Desktop.
//logic
exports.getProducts = (req, res, next) => {
const page = +req.query.page || 1;
let totalItems;
Product.find()
.countDocuments()
.then(numProducts => {
totalItems = numProducts;
return Product.find()
.skip((page - 1) * ITEMS_PER_PAGE)
.limit(ITEMS_PER_PAGE);
})
.then(products => {
res.render('shop/product-list', {
prods: products,
pageTitle: 'Products',
path: '/products',
currentPage: page,
hasNextPage: ITEMS_PER_PAGE * page < totalItems,
hasPreviousPage: page > 1,
nextPage: page + 1,
previousPage: page - 1,
lastPage: Math.ceil(totalItems / ITEMS_PER_PAGE)
});
})
.catch(err => {
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
};
//view
<section class="pagination">
<% if (currentPage !== 1 && previousPage !== 1) { %>
<a href="?page=1">1</a>
<% } %>
<% if (hasPreviousPage) { %>
<a href="?page=<%= previousPage %>"><%= previousPage %></a>
<% } %>
<a href="?page=<%= currentPage %>" class="active"><%= currentPage %></a>
<% if (hasNextPage) { %>
<a href="?page=<%= nextPage %>"><%= nextPage %></a>
<% } %>
<% if (lastPage !== currentPage && nextPage !== lastPage) { %>
<a href="?page=<%= lastPage %>"><%= lastPage %></a>
<% } %>
</section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment