Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ Promise fulfilled with object having properties:
* `limit` {Number} - Limit that was used
* `[page]` {Number} - Only if specified or default `page`/`offset` values were used
* `[pages]` {Number} - Only if `page` specified or default `page`/`offset` values were used
* `[prev]` {Number} - Only if there is a previous page to go to.
* `[next]` {Number} - Only if there is a next page to go to.
* `[offset]` {Number} - Only if specified or default `page`/`offset` values were used

### Examples
Expand Down
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ function paginate(query, options, callback) {
if (page !== undefined) {
result.page = page;
result.pages = Math.ceil(data.count / limit) || 1;
let prev = page - 1;
let next = page + 1;

if (prev > 0) {
result.prev = prev;
}

if (next <= result.pages) {
result.next = next;
}
}
if (typeof callback === 'function') {
return callback(null, result);
Expand Down
26 changes: 26 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,35 @@ describe('mongoose-paginate', function() {
expect(result.limit).to.equal(20);
expect(result.page).to.equal(1);
expect(result.pages).to.equal(5);
expect(result.next).to.equal(2);
expect(result.prev).to.be.undefined;
expect(result).to.not.have.property('offset');
});
});
it('on the first page', function() {
return Book.paginate({}, { page: 1, limit: 20 }).then(function(result) {
expect(result.next).to.equal(2);
expect(result).to.not.have.property('prev');
});
});
it('on the last page', function() {
return Book.paginate({}, { page: 5, limit: 20 }).then(function(result) {
expect(result.prev).to.equal(4);
expect(result).to.not.have.property('next');
});
});
it('on the middle page', function() {
return Book.paginate({}, { page: 3, limit: 20 }).then(function(result) {
expect(result.prev).to.equal(2);
expect(result.next).to.equal(4);
});
});
it('with page 1 and limit', function() {
return Book.paginate({}, { page: 1, limit: 20 }).then(function(result) {
expect(result.next).to.equal(2);
expect(result).to.not.have.property('prev');
});
});
it('with zero limit', function() {
return Book.paginate({}, { page: 1, limit: 0 }).then(function(result) {
expect(result.docs).to.have.length(0);
Expand Down