Skip to content

Instantly share code, notes, and snippets.

@craftgear
Created December 28, 2011 02:44
Show Gist options
  • Save craftgear/1525918 to your computer and use it in GitHub Desktop.
Save craftgear/1525918 to your computer and use it in GitHub Desktop.
Mongoose Pagination
# 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.")
@mararual
Copy link

Hi.

Thanks for the code. Where should I put these? I can't get it to work outside of query.js

@craftgear
Copy link
Author

Hi, there.

To use this code, save it as a file named 'paginate.coffee' and require it in any scripts.
In your codes, call the 'paginate' method at the last of any models' method chain.

Hope this helps you.

@mararual
Copy link

mararual commented Jul 14, 2012 via email

@nicolashery
Copy link

@craftgear Thanks for this!

You would need to replace query.run with query.exec for the newest version of Mongoose though...

Also, I forked this to make a pure JavaScript version, and also to allow either offset or page to be specified:
https://gist.github.com/nicolahery/5327344

Cheers!
Nicolas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment