Created
April 27, 2019 20:29
-
-
Save bishoymelek-zz/b2d32429a70179e14841c3b1f7190e3c to your computer and use it in GitHub Desktop.
example for get data from mongodb with mongoose in express app with pagination( without additional npm packages)
This file contains hidden or 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
app.get('/:pageNum', function (req, res) { | |
try { | |
// how many to items to load everytime | |
const perPage = 12; | |
// which page is current? | |
const page = req.params.pageNum || 1; | |
// find all | |
ClientModel.find({}) | |
// skip number of items (number of pages we passed * number of items per page) minus one of that number of | |
// items per page (to get the current one we get as param) | |
.skip((perPage * page) - perPage) | |
// limit number of items to fetch to be as defined from since started | |
.limit(perPage) | |
.exec(function (err, data) { | |
// how many items we have? (gonna divide that amount over number of items per page | |
ClientModel.count().exec(function (err, count) { | |
if (err) { | |
logger.error(`CRUD_CLIENT/GET_ALL error:${err}`); | |
res.status(500) | |
.json({ success: false, message: "Internal server error" }); | |
} else { | |
res.status(200).json({ | |
success: true, message: "data loaded successfully", data: data, pages: { | |
current: page, | |
total: Math.ceil(count / perPage) | |
} | |
}); | |
} | |
}); | |
}); | |
} catch (error) { | |
logger.error(`CRUD_CLIENT/GET_ALL error:${err}`); | |
next(error); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment