0

I am using mongoose pagination v5.0.3, node 9.3.0. I have this code for my blogs pagination:

 router.get('/pages/:page', function(req, res){
     var page = req.params.page > 0? req.params.page : 0;

     Blog.paginate({}, { page: page, limit: 2 })
       .then(function(data){
           res.render('blog/index', {blog: data.docs});
       }).catch(function(err){
           res.send(err)
     });
 });

This code works fine when the page loads, but when I refresh the page it loads 'not found page' app.get("*", function(req, res) { res.render("pages/404page"); });

Alisher Musurmonv
  • 815
  • 1
  • 9
  • 18

2 Answers2

1

It actually isn't that pagination function. It is this regex statement above:

router.param('page', /[0-9]/g)

Remove the 'g' and it will work.

Explanation:

You're using a g (global) RegExp. In JavaScript, global regexen have state: you call them (with exec, test etc.) the first time, you get the first match in a given string. Call them again and you get the next match, and so on until you get no match and it resets to the start of the next string.

Source

Btw, your regex only checks digits from 0-9, you might want that to take into digits higher than 9, if you are expecting more than 10 blog posts.

thomann061
  • 629
  • 3
  • 11
0

You can do same using find skip and limit.

router.get('/pages/:page', function (req, res) {
    var page = req.params.page > 0 ? req.params.page : 0;
    var limit = 2;
    Blog.find({})
        .limit(limit)
        .skip(limit * page)
        .exec()
        .then(function (data) {
            res.render('blog/index', {
                blog: data.docs
            });
        }).catch(function (err) {
            res.send(err)
        });
});
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37