Skip to content

Instantly share code, notes, and snippets.

@pizzarob
Created October 12, 2016 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pizzarob/9dfc94ad79cc342d604cdbe5ee2cf5dc to your computer and use it in GitHub Desktop.
Save pizzarob/9dfc94ad79cc342d604cdbe5ee2cf5dc to your computer and use it in GitHub Desktop.
function paginate(query = {}, options = {}, callback) {
const limit = options.limit || 10;
let page = options.page || 1;
const countQuery = this.find(query).count();
return new Promise(resolve => {
countQuery.exec().then(count => {
const pages = Math.ceil(count / limit) || 1;
if (page > pages) {
page = pages;
}
const skip = (page - 1) * limit;
let docsQuery = this.find(query)
.sort(options.sort)
.skip(skip)
.limit(limit);
docsQuery.exec().then(docs => {
resolve({
count,
docs,
page,
limit,
pages,
});
});
});
});
}
export default function(schema) {
schema.statics.paginate = paginate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment