Created
October 12, 2016 19:47
-
-
Save pizzarob/9dfc94ad79cc342d604cdbe5ee2cf5dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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