Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@mararual mararual commented Jul 13, 2012

Hi.

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

@craftgear

This comment has been minimized.

Copy link
Owner Author

@craftgear craftgear commented Jul 13, 2012

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

This comment has been minimized.

Copy link

@mararual mararual commented Jul 14, 2012

@nicolashery

This comment has been minimized.

Copy link

@nicolashery nicolashery commented Apr 6, 2013

@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