Last active
November 21, 2017 11:51
-
-
Save clauda/5167747 to your computer and use it in GitHub Desktop.
Mongoose Pagination #NodeJS #Express #MongoDB
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
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.'); } | |
}; | |
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
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