Skip to content

Instantly share code, notes, and snippets.

@clauda
Last active November 21, 2017 11:51
Embed
What would you like to do?
Mongoose Pagination #NodeJS #Express #MongoDB
var mongoose = require('mongoose');
mongoose.Query.prototype.paginate = function(page, limit, callback) {
var query = this
, page = page || 1
, limit = limit || 10
, offset = (limit * page) - limit;
query = query.skip(offset).limit(limit);
if(callback){
query.exec(function(err, data) {
if(err){ callback(err, null, null) }
else {
query.model.count(query._conditions, function(err, count) {
callback(null, count, data);
});
}
});
} else { throw new Error('pagination needs a callback as the third argument.'); }
};
paginate = require('./lib/pagine')
var database = require('./config/database')
, User = require('./foster').User
// ...
exports.threads = function(request, response) {
response.setHeader("Content-Type", "application/json");
User.find({}).paginate(request.query.page, 10, function(err, count, data) {
response.end(JSON.stringify(data));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment