Last active
April 16, 2020 15:41
-
-
Save kluu1/91032cc2207fb6ee88c6f7be8a393a2e to your computer and use it in GitHub Desktop.
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('/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