Skip to content

Instantly share code, notes, and snippets.

@kluu1
Last active April 16, 2020 15:41
Show Gist options
  • Save kluu1/91032cc2207fb6ee88c6f7be8a393a2e to your computer and use it in GitHub Desktop.
Save kluu1/91032cc2207fb6ee88c6f7be8a393a2e to your computer and use it in GitHub Desktop.
app.get('/posts', async (req, res) => {
// destructure page and limit and set default values
const { page = 1, limit = 10 } = req.query;
try {
// execute query with page and limit values
const posts = await Posts.find()
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();
// get total documents in the Posts collection
const count = await Posts.countDocuments();
// return response with posts, total pages, and current page
res.json({
posts,
totalPages: Math.ceil(count / limit),
currentPage: page
});
} catch (err) {
console.error(err.message);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment