Last active
September 7, 2018 16:47
-
-
Save aymenbz/097843088d21118df4bcb5b89dc1ebba to your computer and use it in GitHub Desktop.
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
// From https://codeforgeek.com/2017/12/server-side-pagination-using-node-and-mongo/ | |
router.get('/users',(req,res) => { | |
var pageNo = parseInt(req.query.pageNo) | |
var size = parseInt(req.query.size) | |
var query = {} | |
if(pageNo < 0 || pageNo === 0) { | |
response = {"error" : true,"message" : "invalid page number, should start with 1"}; | |
return res.json(response) | |
} | |
query.skip = size * (pageNo - 1) | |
query.limit = size | |
// Find some documents | |
mongoOp.count({},function(err,totalCount) { | |
if(err) { | |
response = {"error" : true,"message" : "Error fetching data"} | |
} | |
mongoOp.find({},{},query,function(err,data) { | |
// Mongo command to fetch all data from collection. | |
if(err) { | |
response = {"error" : true,"message" : "Error fetching data"}; | |
} else { | |
var totalPages = Math.ceil(totalCount / size) | |
response = {"error" : false,"message" : data,"pages": totalPages}; | |
} | |
res.json(response); | |
}); | |
}) | |
exp: http://localhost:3000/api/users?pageNo=1&size=10 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment