Skip to content

Instantly share code, notes, and snippets.

@bishoymelek-zz
Created April 27, 2019 20:29
Show Gist options
  • Save bishoymelek-zz/b2d32429a70179e14841c3b1f7190e3c to your computer and use it in GitHub Desktop.
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)
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