I followed https://github.com/expressjs/express-paginate#example tutorial to implement pagination in NodeJS with express-paginator
All is working well but the issue is when i click on the last page number hyperlink it keeps on redirecting me to a new incremented page number with no records displayed as there's no document in collection
For e.g if the last page number is 2 and i click on two it will keep on redirecting me to http://127.0.0.1:3000/users?page=3 again i click and again it gives http://127.0.0.1:3000/users?page=4
Can anyone please help me out?
Below is the route file : users.js
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'), //mongo connection
bodyParser = require('body-parser'), //parses information from POST
methodOverride = require('method-override'); //used to manipulate POST
multipart = require("connect-multiparty");
multiparty = multipart();
fs = require('fs');
session = require('express-session');
paginate = require('express-paginate');
router.use(bodyParser.urlencoded({ extended: true }))
router.use(methodOverride(function(req, res){
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
var method = req.body._method
delete req.body._method
return method
}
}))
var sess;
router.route('/')
//GET all users
.get(function(req, res, next) {
//retrieve all users from MongoDB
sess = req.session;
if(sess.user){
mongoose.model('User').paginate({}, { page: req.query.page, limit: req.query.limit }, function(err, users) {
if (err) {
return console.error(err);
} else {
//respond to both HTML and JSON. JSON responses require 'Accept: application/json;' in the Request Header
res.format({
//HTML response will render the users.jade file in the views/account folder. We are also setting "users" to be an accessible variable in our jade view
html: function(){
res.render('account/users', {
title: 'Users',
"users" : users.docs,
pageCount: users.pages,
itemCount: users.total,
pages: res.locals.paginate.getArrayPages(3, users.pages, 1),
has_more : res.locals.paginate.hasNextPages(users.pages)
});
},
//JSON response will show all blobs in JSON format
json: function(){
res.json({
object: 'list',
has_more: res.locals.paginate.hasNextPages(users.pages),
data: users.docs
});
}
});
}
});
}else{
res.redirect('/login');
}
})
module.exports = router;
paginate.jade
if paginate.hasPreviousPages || paginate.hasNextPages(pageCount)
.navigation.well-sm#pagination
ul.pager
if paginate.hasPreviousPages
li.previous
a(href=paginate.href(true)).prev
i.fa.fa-arrow-circle-left
| Previous
if pages
each page in pages
a.btn.btn-default(href=page.url)= page.number
if paginate.hasNextPages(pageCount)
li.next
a(href=paginate.href()).next
| Next
i.fa.fa-arrow-circle-right
Thanks in Advance..!!
via ankita simlai
No comments:
Post a Comment