Coder Social home page Coder Social logo

express-paginate's Introduction

express-paginate

NPM Version NPM Downloads Build Status Test Coverage MIT License Slack

Node.js pagination middleware and view helpers.

Looking for a Koa version? Try using https://github.com/koajs/ctx-paginate, which is forked directly from this package!

v0.2.0+: As of v0.2.0, we now allow you to pass ?limit=0 to get infinite (all) results. This may impose security or performance issues for your application, so we suggest you to write a quick middleware fix such as the one below, or use rate limiting middleware to prevent abuse.

app.all(function(req, res, next) {
  // set default or minimum is 10 (as it was prior to v0.2.0)
  if (req.query.limit <= 10) req.query.limit = 10;
  next();
});

Install

npm install -S express-paginate

API

const paginate = require('express-paginate');

paginate

This creates a new instance of express-paginate.

paginate.middleware(limit, maxLimit)

This middleware validates and supplies default values to req.skip (an alias of req.offset, which can be used to skip or offset a number of records for pagination, e.g. with Mongoose you would do Model.find().skip(req.skip)), req.query.limit, req.query.page, res.locals.paginate, res.locals.hasPreviousPages, and res.locals.hasNextPages.

Arguments

  • limit a Number to limit results returned per page (defaults to 10)
  • maxLimit a Number to restrict the number of results returned to per page (defaults to 50) – through this, users will not be able to override this limit (e.g. they can't pass ?limit=10000 and crash your server)

paginate.href(req)

When you use the paginate middleware, it injects a view helper function called paginate.href as res.locals.paginate, which you can use in your views for paginated hyperlinks (e.g. as the href in <a>Prev</a> or <a>Next</a>).

By default, the view helper paginate.href is already executed with the inherited req variable, therefore it becomes a function capable of returning a String when executed.

When executed with req, it will return a function with two optional arguments, prev (Boolean) and params (String).

The argument prev is a Boolean and is completely optional (defaults to false).

The argument params is an Object and is completely optional.

Pass true as the value for prev when you want to create a <button> or <a> that points to the previous page (e.g. it would generate a URL such as the one in the href attribute of <a href="/users?page=1&limit=10">Prev</a> if req.query.page is 2).

Pass an object for the value of params when you want to override querystring parameters – such as for filtering and sorting (e.g. it would generate a URL such as the one in the href attribute of <a href="/users?page=1&limit=10&sort=name">Sort By Name</a> if params is equal to { sort: 'name' }.

Note that if you pass only one argument with a type of Object, then it will generate a href with the current page and use the first argument as the value for params. This is useful if you only want to do something like change the filter or sort querystring param, but not increase or decrease the page number.

See the example below for an example of how implementation looks.

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • prev (optional) – a Boolean to determine whether or not to increment the hyperlink returned by 1 (e.g. for "Next" page links)
  • params (optional) – an Object of querystring parameters that will override the current querystring in req.query (note that this will also override the page querystring value if page is present as a key in the params object) (e.g. if you want to make a link that allows the user to change the current querystring to sort by name, you would have params equal to { sort: 'name' })

paginate.hasPreviousPages

When you use the paginate middleware, it injects a view helper Boolean called hasPreviousPages as res.locals.hasPreviousPages, which you can use in your views for generating pagination <a>'s or <button>'s – this utilizes req.query.page > 1 to determine the Boolean's resulting value (representing if the query has a previous page of results)

paginate.hasNextPages(req)

When you use the paginate middleware, it injects a view helper function called hasNextPages as res.locals.hasPreviousPages, which you can use in your views for generating pagination <a>'s or <button>'s – if the function is executed, it returns a Boolean value (representing if the query has another page of results)

By default, the view helper paginate.hasNextPages is already executed with the inherited req variable, therefore it becomes a function capable of returning a Boolean when executed.

When executed with req, it will return a function that accepts two required arguments called pageCount and resultsCount.

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • pageCount (required) – a Number representing the total number of pages for the given query executed on the page

paginate.getArrayPages(req)

Get all the page urls with limit. petronas contest 2015-10-29 12-35-52

Arguments

  • req (required) – the request object returned from Express middleware invocation

Returned function arguments when invoked with req

  • limit (optional) – Default: 3, a Number representing the total number of pages for the given query executed on the page.
  • pageCount (required) – a Number representing the total number of pages for the given query executed on the page.
  • currentPage (required) – a Number representing the current page.

Example with mongoose ODM (see example 2 for Sequelize ORM)

// # app.js

const express = require('express');
const paginate = require('express-paginate');
const app = express();

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.get('/users', async (req, res, next) => {

  // This example assumes you've previously defined `Users`
  // as `const Users = db.model('Users')` if you are using `mongoose`
  // and that you are using Node v7.6.0+ which has async/await support
  try {

    const [ results, itemCount ] = await Promise.all([
      Users.find({}).limit(req.query.limit).skip(req.skip).lean().exec(),
      Users.count({})
    ]);

    const pageCount = Math.ceil(itemCount / req.query.limit);

    if (req.accepts('json')) {
      // inspired by Stripe's API response for list objects
      res.json({
        object: 'list',
        has_more: paginate.hasNextPages(req)(pageCount),
        data: results
      });
    } else {
      res.render('users', {
        users: results,
        pageCount,
        itemCount,
        pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)
      });
    }

  } catch (err) {
    next(err);
  }

});

app.listen(3000);

Example 2 with Sequelize ORM

// # app.js

const express = require('express');
const paginate = require('express-paginate');
const app = express();

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.get('/users', async (req, res, next) => {

  // This example assumes you've previously defined `Users`
  // as `const Users = sequelize.define('Users',{})` if you are using `Sequelize`
  // and that you are using Node v7.6.0+ which has async/await support

  router.get("/all_users", (req, res, next) => {
    db.User.findAndCountAll({limit: req.query.limit, offset: req.skip})
      .then(results => {
        const itemCount = results.count;
        const pageCount = Math.ceil(results.count / req.query.limit);
        res.render('users/all_users', {
          users: results.rows,
          pageCount,
          itemCount,
          pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)
        });
    }).catch(err => next(err))
  });

});

app.listen(3000);
//- users.pug

h1 Users

//- this will simply generate a link to sort by name
//- note how we only have to pass the querystring param
//- that we want to modify here, not the entire querystring
a(href=paginate.href({ sort: 'name' })) Sort by name

//- this assumes you have `?age=1` or `?age=-1` in the querystring
//- so this will basically negate the value and give you
//- the opposite sorting order (desc with -1 or asc with 1)
a(href=paginate.href({ sort: req.query.age === '1' ? -1 : 1 })) Sort by age

ul
  each user in users
    li= user.email

include _paginate
//- _paginate.pug

//- This examples makes use of Bootstrap 3.x pagination classes

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&nbsp;
            i.fa.fa-arrow-circle-right

License

MIT

express-paginate's People

Contributors

b3rn475 avatar chadfurman avatar esco avatar hugoduraes avatar khanghoang avatar leonardo0543 avatar niftylettuce avatar rajivnarayana avatar rotem-bar avatar simison avatar ultimate-tester avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

express-paginate's Issues

how to set first and last link?

page.url - current link
paginate.href(true) - prev link
paginate.href() - next link

How to add the first and last link, if I, for example, on page 50?

And the second question - how to disable the parameter limit in the URL?

Incompatibility with express 5

Hi everyone,
this is just to leave a note to everyone who's looking for this info. At the current state this module is not compatible with express 5, because they changed the req.query object in a getter, so this library is not able to add page and limit to it.
Cheers.

Infinite scroll

Hi, one question. This library support Infinite scroll, It is within the scope of the library?. If not, I could send a PR ?.

Thanks!

Display group button of pages

Hi,
I think this is very convenient view helper. But in my case, I wanna have group button of pages like image below:

petronas contest 2015-10-29 12-35-52

I think it makes sense when you deal with data table in CMS

How to send "skip" parameter?

Hi everyone,

In your example, I see this code limit(req.query.limit).skip(req.skip).lean().exec(),

About the "limit" parameter, I can send it from client without problem (I'm using Axios)

But for the "skip" parameter, I don't know how to send that value? Because it doesn't belong to req.query, req.params or req.body.

How can I send the value for "skip"?

Thanks.

Error: express-paginate: `limit` is not a number >= 0

I'm using
express-paginate and mongoose-paginate

have latest version of all
file structure is express-generator
this error occurs everytime at

pages: paginate.getArrayPages(req)(3, pageCount, req.query.page)

my code is like
pages: res.locals.paginate.getArrayPages(req)(3, categories.pages, 1)
When I comment this line
page renders succesfully but I cannot create links afterwards

routes/category.js

function getAllRecords(req , res , next){
    console.log("getAllRecords");
    var Category = res.categoryModel ; // models/categoryModel.js
     Category.paginate({}, { page: req.query.page, limit: req.query.limit }, function(err, categories) {
 if (err) throw err;
res.format({
            html: function() {
                res.render('category/admin', {
                models: categories.docs,
                'res':res,
                pageCount: categories.pages,
                itemCount: categories.total,
                pages: res.locals.paginate.getArrayPages(req)(3, categories.pages, 1)
                });
            },
            json: function() {
                // inspired by Stripe's API response for list objects
                res.json({
                object: 'list',
                has_more: res.locals.paginate.hasNextPages(req)(categories.pages),
                data: categories.docs
                });
            }
        });

    });


}


app.js

ar app = express();
// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));
/***** Models ********/
var categoryModel = require('./models/categoryModel');
var modelsInsideCategoryController = {'categoryModel':categoryModel};
var category = require('./routes/category')(modelsInsideCategoryController);
app.use('/category', category);


models/categoryModel.js

// grab the things we need
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
// create a schema
var categorySchema = new Schema({
  name: {type:String,required:true},
  created_at: Date,
  updated_at: Date
});
categorySchema.plugin(mongoosePaginate);
var Category = mongoose.model('Category', categorySchema);
make this available to our users in our Node applications
module.exports = Category;

Something wrong with paginate.getArrayPages

When I exec the following code in my express demo

var pages = paginate.getArrayPages(req)(3, 2, 2);
pages.forEach(function(page) {
    console.log(page);
});

I get the following ouput

 { number: 0, url: '/products?page=0&limit=10' }
 { number: 1, url: '/products?page=1&limit=10' }
 { number: 2, url: '/products?page=2&limit=10' }

Allow specifying minLimit

Since we can now pass ?limit0, would it be worth adding an optional, third parameter to the middleware function, such that:

exports.middleware = function middleware(limit, maxLimit, minLimit) {

}

The alternative is doing something as follows, if we care about order of min and max:

exports.middleware = function middleware(limit, minOrMaxLimit, maxLimit) {
  let minLimit = 0;
  if (maxLimit) {
    minLimit = minOrMaxLimit;
  }

}

Different limits for multiple resources

I have two different resources and I want to control the limit for each one.

Resource 1 needs a limit of 9, and resource 2 needs a 25 limit. How can I achieve this? Seems the middleware sets the same limit for each.

I have tried:

app.use('/resource1', paginate.middleware(9, 18))
app.use('/resource2', paginate.middleware(25, 100))

But this doesn't work as you may imagine.

Documentation example errors

Hello, I read the example from documentation but i encounter some errors.
The correct example is this:

var express = require('express');
var paginate = require('express-paginate');
var app = express();

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.get('/users', function(req, res, next) {

  //
  // TODO: The documentation has changed for `mongoose-paginate`
  // as the original author unpublished and then published it (not sure why)
  // but the API has changed, so this example is no longer relevant or accurate
  // see <https://github.com/edwardhotchkiss/mongoose-paginate>
  //
  // This example assumes you've previously defined `Users`
  // as `var Users = db.model('Users')` if you are using `mongoose`
  // and that you've added the Mongoose plugin `mongoose-paginate`
  // to the Users model via `User.plugin(require('mongoose-paginate'))`
  Users.paginate({}, { page: req.query.page, limit: req.query.limit }, function(err, result) {

    if (err) return next(err);

    res.format({
      html: function() {
        res.render('users', {
          users: result.docs,
          pageCount: pageCount,
          itemCount: itemCount,
          pages: paginate.getArrayPages(req)(3, result.pages, req.query.page)
        });
      },
      json: function() {
        // inspired by Stripe's API response for list objects
        res.json({
          object: 'list',
          has_more: paginate.hasNextPages(req)(result.pages),
          data: result.docs
        });
      }
    });

  });

});

app.listen(3000);

RethinkDB

Hello,

Is there an example of how to use this with RethinkDB?

Any tutorial would be greatly appreciated.

Update documentation

I kindly ask for a working example with the latest version of Mongoose-paginate. Is there any documentation one can use when implementing pagination with the suggested module for database queries (mongoose-paginate)?

Example with EJS

Hello, I'm trying to port the Jade example to EJS with no result, help me please!

Paginate only show first page

User is show to limit to next page
http://localhost:1500/categories?page=2&limit=4
but the result only show first pages data query..

router.get('/', function(req, res, next) {
  models.Category.findAndCountAll({limit:req.query.limit,offset:req.skip}).then(results=>{
    const itemCount = results.count;
    const pageCount = Math.ceil(results.count / req.query.limit); 
    res.render('categories/list', {
              cats:results.rows,
              pageCount,
              itemCount,
              pages:paginate.getArrayPages(req)(3, pageCount, req.query.page)

            });
        });
});

image

Remove GitHub URL in description

@jonathanong can you remove the GitHub URL in description that's currently pointing to a broken link on DocumentUp? I think it's fine to just have the Readme and not have some generated docs.

Sorting data

Hi,

I'm using your module for my website, but I can't figure how to sort my data before paginating?

Thanks.

Wrong Offset

I thing the minimum offset value of 1 is actually wrong. It will alwais point to the second page.

implement "promises bluebird"

Hello, in the example it shows how to implement the code with callbacks but now that mongoose does not allow queries that way, I use the query so promise as says the documentation of "mongoose-promise" to work properly but I the following error:

I want to know how to write properly used promises
Error: express-paginate:pageCountis not a number >= 0 at C:\Users\Oscar\Desktop\OCT\node_modules\express-paginate\index.js:65:13 at C:\Users\Oscar\Desktop\OCT\App\Routes\admin-profesores.js:29:46 at tryCatcher (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\util.js:11:23) at Promise._settlePromiseFromHandler (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:488:31) at Promise._settlePromise (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:545:18) at Promise._settlePromise0 (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:590:10) at Promise._settlePromises (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:673:18) at Promise._fulfill (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:614:18) at Promise._resolveCallback (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:415:57) at Promise._settlePromiseFromHandler (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:501:17) at Promise._settlePromise (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:545:18) at Promise._settlePromise0 (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:590:10) at Promise._settlePromises (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:673:18) at Promise._fulfill (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:614:18) at PropertiesPromiseArray.PromiseArray._resolve (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise_array.js:125:19) at PropertiesPromiseArray._promiseFulfilled (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\props.js:78:14) at Promise._settlePromise (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:550:26) at Promise._settlePromise0 (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:590:10) at Promise._settlePromises (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\promise.js:673:18) at Async._drainQueue (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\async.js:125:16) at Async._drainQueues (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\async.js:135:10) at Immediate.Async.drainQueues [as _onImmediate] (C:\Users\Oscar\Desktop\OCT\node_modules\mongoose-paginate\node_modules\bluebird\js\release\async.js:16:14) at processImmediate [as _immediateCallback] (timers.js:383:17)

Here my code that returns the error

`router.route("/")
.get(function (sol, res, next) {
locals={
tipoDeUsuairo: "Profesor",
title: "Profesores",
page_title: "Panel de Profesores"};

        //codigo con paginacion
        Profesor.paginate({tipo:"PROFESOR"}, {page: sol.query.page, limit: sol.query.limit})
            .then(function (profes, pageCount, itemCount) {
            locals.profes = profes.docs;
            locals.pageCount =  pageCount;
            locals.itemCount = itemCount;
            locals.page = paginate.getArrayPages(sol)(3, pageCount, sol.query.page);
            res.render("Admin/Profesores/index", locals);
        }).catch(function (err) {
            //res.json(err);
            if (err) return next(err);
        })

    })`

Handlebars paginate.href true gives weird value

Hello i am trying to make previous button in handlebars
<a href="{{paginate.href true}}" class="paginator-itemLink">Prev</a>
Well it works it goes back but url looks like this
http://localhost:3000/users/show?page=3&limit=5&name=paginate.href&data%5Bexphbs%5D%5Bcache%5D=false&data%5Bexphbs%5D%5Bview%5D=..%5Cmodules%5Cusers%5Cviews%5CuserList&data%5Bexphbs%5D%5Blayout%5D=cmsLayout&data%5Bexphbs%5D%5BfilePath%5D=C%3A%5CUsers%5CJuraj%20Jakubov%5CPraca%5CWebov%C3%A9%20aplik%C3%A1cie%5CNodeCMS%5Cmodules%5Cusers%5Cviews%5CuserList.handlebars&data%5B_parent%5D%5Bexphbs%5D%5Bcache%5D=false&data%5B_parent%5D%5Bexphbs%5D%5Bview%5D=..%5Cmodules%5Cusers%5Cviews%5CuserList&data%5B_parent%5D%5Bexphbs%5D%5Blayout%5D=cmsLayout&data%5B_parent%5D%5Bexphbs%5D%5BfilePath%5D=C%3A%5CUsers%5CJuraj%20Jakubov%5CPraca%5CWebov%C3%A9%20aplik%C3%A1cie%5CNodeCMS%5Cmodules%5Cusers%5Cviews%5CuserList.handlebars&data%5Broot%5D%5Bsettings%5D%5Bx-powered-by%5D=true&data%5Broot%5D%5Bsettings%5D%5Betag%5D=weak&data%5Broot%5D%5Bsettings%5D%5Benv%5D=development&data%5Broot%5D%5Bsettings%5D%5Bquery%20parser%5D=extended&data%5Broot%5D%5Bsettings%5D%5Bsubdomain%20offset%5D=2&data%5Broot%5D%5Bsettings%5D%5Bviews%5D=C%3A%5CUsers%5CJuraj%20Jakubov%5CPraca%5CWebov%C3%A9%20aplik%C3%A1cie%5CNodeCMS%5Cviews&data%5Broot%5D%5Bsettings%5D%5Bjsonp%20callback%20name%5D=callback&data%5Broot%5D%5Buser%5D=&data%5Broot%5D%5BcsrfToken%5D=NDvvfCUK-51L1-xOQagieUfzN3nNSJTLR5mc&data%5Broot%5D%5Bpaginate%5D%5Bpage%5D=4&data%5Broot%5D%5Bpaginate%5D%5Blimit%5D=5&data%5Broot%5D%5Bpaginate%5D%5BhasPreviousPages%5D=true&data%5Broot%5D%5Blayout%5D=cmsLayout&data%5Broot%5D%5Busers%5D%5B0%5D%5B_id%5D%5B_bsontype%5D=ObjectID&data%5Broot%5D%5Busers%5D%5B0%5D%5B_id%5D%5Bid%5D=%5C%029%EF%BF%BD%2B%EF%BF%BD%EF%BF%BD%40Dv%3C%EF%BF%BD&data%5Broot%5D%5Busers%5D%5B0%5D%5Bfirstname%5D=xxxxxxxxxfsdf&data%5Broot%5D%5Busers%5D%5B0%5D%5Blastname%5D=6j2gh6jhgdfdsfgfgdggfddffdfdghgfxxxxxxxxxfsdf&data%5Broot%5D%5Busers%5D%5B0%5D%5Bemail%5D=xxxxxxxxxfsdf%40xxxxxxxxxfsdf.com&data%5Broot%5D%5Busers%5D%5B0%5D%5Bpassword%5D=%242a%2410%24ktxWt.LVWrlcn2OTNK7w0.gv7cgKAxrTkAvqEUYAyRZqhPO4Rr196&data%5Broot%5D%5Busers%5D%5B0%5D%5Bipadress%5D=%3A%3A1&data%5Broot%5D%5Busers%5D%5B0%5D%5Bcreated%5D=2018-12-01T07%3A34%3A45.718Z&data%5Broot%5D%5Busers%5D%5B0%5D%5Bprovider%5D=local&data%5Broot%5D%5Busers%5D%5B0%5D%5Bstatus%5D=0&data%5Broot%5D%5Busers%5D%5B0%5D%5BsecretToken%5D=QnEDBzliiEGA4Aj5VXXkarIWIgaHy0Hk&data%5Broot%5D%5Busers%5D%5B0%5D%5B__v%5D=0&data%5Broot%5D%5Busers%5D%5B1%5D%5B_id%5D%5B_bsontype%5D=ObjectID&data%5Broot%5D%5Busers%5D%5B1%5D%5B_id%5D%5Bid%5D=%5C%029%EF%BF%BD%2B%EF%BF%BD%EF%BF%BD%40Dv%3C%EF%BF%BD&data%5Broot%5D%5Busers%5D%5B1%5D%5Bfirstname%5D=xxxxxxxxxfsdffsd&data%5Broot%5D%5Busers%5D%5B1%5D%5Blastname%5D=6j2gh6jhgdfdsfgfsdffgdggfddffdfdghgfxxxfsdxxxxxxfsdf&data%5Broot%5D%5Busers%5D%5B1%5D%5Bemail%5D=xxxxxxxfdsxxfsdf%40xxxxxfsdxxxxfsdf.com&data%5Broot%5D%5Busers%5D%5B1%5D%5Bpassword%5D=%242a%2410%24vB%2FOUFuqOcGKg7DOmxraJO7SzCm54vn.jkKbc3cMSKyrCBNfkUuIm&data%5Broot%5D%5Busers%5D%5B1%5D%5Bipadress%5D=%3A%3A1&data%5Broot%5D%5Busers%5D%5B1%5D%5Bcreated%5D=2018-12-01T07%3A34%3A51.523Z&data%5Broot%5D%5Busers%5D%5B1%5D%5Bprovider%5D=local&data%5Broot%5D%5Busers%5D%5B1%5D%5Bstatus%5D=0&data%5Broot%5D%5Busers%5D%5B1%5D%5BsecretToken%5D=i4ZcErC8PMLvQIq0uTsRWVnqxObPFKMQ&data%5Broot%5D%5Busers%5D%5B1%5D%5B__v%5D=0&data%5Broot%5D%5Busers%5D%5B2%5D%5B_id%5D%5B_bsontype%5D=ObjectID&data%5Broot%5D%5Busers%5D%5B2%5D%5B_id%5D%5Bid%5D=%5C%029%EF%BF%BD%2B%EF%BF%BD%EF%BF%BD%40Dv%3C%EF%BF%BD&data%5Broot%5D%5Busers%5D%5B2%5D%5Bfirstname%5D=xxxxxxxxxfsdffsdf&data%5Broot%5D%5Busers%5D%5B2%5D%5Blastname%5D=6j2gh6jhgdfdsfgfsdffgdggfddffdfdghgfxxfxfsdxxxxxxfsdf&data%5Broot%5D%5Busers%5D%5B2%5D%5Bemail%5D=xxxxxxxfdfsxxfsdf%40xxxxxfsdxxxxfsdf.com&data%5Broot%5D%5Busers%5D%5B2%5D%5Bpassword%5D=%242a%2410%24VdE04Mft6TFPXVhoTjHXJOr57VxnFD5tiv5lsf64irSVNqQXm7YRG&data%5Broot%5D%5Busers%5D%5B2%5D%5Bipadress%5D=%3A%3A1&data%5Broot%5D%5Busers%5D%5B2%5D%5Bcreated%5D=2018-12-01T07%3A36%3A18.200Z&data%5Broot%5D%5Busers%5D%5B2%5D%5Bprovider%5D=local&data%5Broot%5D%5Busers%5D%5B2%5D%5Bstatus%5D=0&data%5Broot%5D%5Busers%5D%5B2%5D%5BsecretToken%5D=8pzb0rjCpqSpg3jQek04NRL8cXE3b7sm&data%5Broot%5D%5Busers%5D%5B2%5D%5B__v%5D=0&data%5Broot%5D%5Busers%5D%5B3%5D%5B_id%5D%5B_bsontype%5D=ObjectID&data%5Broot%5D%5Busers%5D%5B3%5D%5B_id%5D%5Bid%5D=%5C%029%EF%BF%BD%2B%EF%BF%BD%EF%BF%BD%40Dv%3C%EF%BF%BD&data%5Broot%5D%5Busers%5D%5B3%5D%5Bfirstname%5D=xxxxxxgfdxxxfsdffsdf&data%5Broot%5D%5Busers%5D%5B3%5D%5Blastname%5D=6j2gh6jhgdfdsfgfsgdfdffgdggfddffdfdghgfxxfxfsdxxxxxxfsdf&data%5Broot%5D%5Busers%5D%5B3%5D%5Bemail%5D=xxxxxxxfdfgfdsxxfsdf%40xxxxxfgfddxxxxfsdf.com&data%5Broot%5D%5Busers%5D%5B3%5D%5Bpassword%5D=%242a%2410%24o3xpsEpYKoqivpOS9Pbqr.j.EXJHPn3sC8yFtqFfien9nYATI6VWm&data%5Broot%5D%5Busers%5D%5B3%5D%5Bipadress%5D=%3A%3A1&data%5Broot%5D%5Busers%5D%5B3%5D%5Bcreated%5D=2018-12-01T07%3A36%3A24.054Z&data%5Broot%5D%5Busers%5D%5B3%5D%5Bprovider%5D=local&data%5Broot%5D%5Busers%5D%5B3%5D%5Bstatus%5D=0&data%5Broot%5D%5Busers%5D%5B3%5D%5BsecretToken%5D=VOv4bEblVtZQK1kUHaYqvKR1T4xryr6u&data%5Broot%5D%5Busers%5D%5B3%5D%5B__v%5D=0&data%5Broot%5D%5BpageCount%5D=4&data%5Broot%5D%5BitemCount%5D=19&data%5Broot%5D%5Bhas_prev%5D=true&data%5Broot%5D%5Bhas_next%5D=false&data%5Broot%5D%5Bpages%5D%5B0%5D%5Bnumber%5D=2&data%5Broot%5D%5Bpages%5D%5B0%5D%5Burl%5D=%2Fusers%2Fshow%3Fpage%3D2%26limit%3D5&data%5Broot%5D%5Bpages%5D%5B1%5D%5Bnumber%5D=3&data%5Broot%5D%5Bpages%5D%5B1%5D%5Burl%5D=%2Fusers%2Fshow%3Fpage%3D3%26limit%3D5&data%5Broot%5D%5Bpages%5D%5B2%5D%5Bnumber%5D=4&data%5Broot%5D%5Bpages%5D%5B2%5D%5Burl%5D=%2Fusers%2Fshow%3Fpage%3D4%26limit%3D5&data%5Broot%5D%5B_locals%5D%5Buser%5D=&data%5Broot%5D%5B_locals%5D%5BcsrfToken%5D=NDvvfCUK-51L1-xOQagieUfzN3nNSJTLR5mc&data%5Broot%5D%5B_locals%5D%5Bpaginate%5D%5Bpage%5D=4&data%5Broot%5D%5B_locals%5D%5Bpaginate%5D%5Blimit%5D=5&data%5Broot%5D%5B_locals%5D%5Bpaginate%5D%5BhasPreviousPages%5D=true&data%5Broot%5D%5Bcache%5D=false

Page URLs wrong after the first page

Issue

Page URLs display as the 'Next' URL after the first page.

Example

Pay attention to the ?page= section URL at the bottom left of the page whilst I scroll across the links.

Page 1 - Works as expected
1

Page 2 (or any page after 1) - Displays the next pages' URL
2

Setup

server.js

var express = require('express');
var paginate = require('express-paginate');
var app = express();

var userController = require('./controllers/user');

app.use(paginate.middleware(1, 12));
app.get('/users', userController.usersGet);

module.exports = app;

controllers/user.js

var paginate = require('express-paginate');

exports.usersGet = function(req, res) {
  User.paginate({}, { page: req.query.page, limit: req.query.limit }, function(err, users) {
    if (err) return next(err)
    res.format({
      html: function() {
        res.render('users', {
          users: users,
          pageCount: users.pages,
          itemCount: users.total,
          pages : res.locals.paginate.getArrayPages(7, users.pages, 1)
        })
      },
      json: function() {
        res.json({
          object: 'list',
          has_more : res.locals.paginate.hasNextPages(users.pages),
          data: users
        })
      }
    })
  })
}

users.jade

ul
  each user in users
    li= user.email

if paginate.hasPreviousPages || paginate.hasNextPages(pageCount)
  .pagination
    if paginate.hasPreviousPages
      a(href=paginate.href(true)) Previous
    else
      a.disabled Previous

    if pages
      each page in pages
        a(class=(paginate.page === page.number) ? 'active' : '', href=page.url)= page.number

    if paginate.hasNextPages(pageCount)
      a(href=paginate.href()) Next
    else
      a.disabled Next

Packages
mongoose: 4.4.8
mongoose-paginate: 5.0.3
express: 4.13.4
express-paginate: 0.2.2

Check integer

Great plugin thanks !

It would be nice if you can check if query strings passed are integer

500 error if I pass ?limit=a

Thanks

Filter using condition

Is it possible to pass a condition to paginate.href()? I tried using paginate.href({ field: 'value' }) but it doesn't seem to work. The tests only reference sort as well.

I would like to filter using a specific value, like users that have the name 'John Doe'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.