Created
December 28, 2011 02:44
-
-
Save craftgear/1525918 to your computer and use it in GitHub Desktop.
Mongoose Pagination
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
# This snippet is inspired by edwardhotchkiss's mongoose-paginate (https://github.com/edwardhotchkiss/mongoose-paginate) | |
# and works with any methods like where, desc, poulate, etc. | |
# | |
# paginate method must be called at the end of method chains. | |
# | |
# paginate = require 'paginate' | |
# model | |
# .find() | |
# .desc("_id") | |
# .populate("some_field") | |
# .paginate(1, 10, (err, total, docs)-> | |
# console.log 'total: ', total, 'docs :', docs | |
# ) | |
mongoose = require 'mongoose' | |
mongoose.Query.prototype.paginate = (page = 1, limit = 10, cb)-> | |
query = this | |
model = this.model | |
skipFrom = (page * limit) - limit | |
query = query.skip(skipFrom).limit(limit) | |
if cb | |
query.run (err, docs)-> | |
if err | |
cb err, null, null | |
else | |
model.count query._conditions, (err, total)-> | |
cb null, total, docs | |
else | |
throw new Error("pagination needs a callback as the third argument.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@craftgear Thanks for this!
You would need to replace
query.run
withquery.exec
for the newest version of Mongoose though...Also, I forked this to make a pure JavaScript version, and also to allow either
offset
orpage
to be specified:https://gist.github.com/nicolahery/5327344
Cheers!
Nicolas