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.") |
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.
Thanks. Worked perfectly! I didn't know it was that easy. I was trying to
create a module and couldn't extend the Query object!
Thanks for your help!
On Fri, Jul 13, 2012 at 4:50 PM, Shunsuke Watanabe < ***@***.*** > wrote:
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.
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/1525918
##
Marcos Aruj Alvarez marcos@linux.com
Ingeniero de Software
_Marcos Aruj_ Supports Linux
Linux Foundation Individual Member
@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
Hi.
Thanks for the code. Where should I put these? I can't get it to work outside of query.js