Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

36
Views
skipping documents in mongodb for pagination

I want to skip some documents according to the page count. For example when I make a GET request to http://localhost:3001/posts?page=2 I want to get 10 documents per page from 10-20.

router/posts.js

const express = require("express");
const {
  getPosts,
  createPost,
  updatePost,
  updateLikeCount,
  getPostById,
  threeLatestPosts,
  deletePost,
  getTenPostsPerPage,
} = require("../controllers/posts");
const verifyToken = require("../utils/verifyToken");

const router = express.Router();

router.get("/threelatest", threeLatestPosts);
router.get("/", getPosts);
router.post("/", verifyToken, createPost);
router.put("/:id", updatePost);
router.get("/:id", getPostById);
router.delete("/delete/:id", verifyToken, deletePost);
// this is how I do the GET request
router.get("/?page=:page", getTenPostsPerPage);

module.exports = router;

Here is what I have tried to skip the document but it doesn't even make the GET request and I don't even get back the console.log

const getTenPostsPerPage = async (req, res) => {
  try {
    console.log("this is not getting logged!")
    const page = req.params.page;
    const perPage = 10;
    const skip = perPage * (page - 1);

    const post = await PostDB.find()
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(perPage);
    if (!post) {
      return res.status(404).json({ message: "Post not found" });
    } else {
      res.status(200).json(post);
    }
  } catch (err) {
    res.status(400).json({ message: err });
  }
};

when I make a GET request http://localhost:3001/posts?page=2 from postman, it returns all the post documents but I expect to get the documents from 10-20. The console.log is not logged in the terminal also.

9 months ago · Santiago Trujillo
1 answers
Answer question

0

I think it's because you are trying to include the querystring as part of the path. If you see the documentation for expressjs here: http://expressjs.com/en/guide/routing.html

have a look at the section "Route paths".

You will see that

Query strings are not part of the route path.

and

The characters ?, +, *, and () are subsets of their regular expression counterparts.

So your question mark is not being interpreted how you expect.

I imagine what is happening is that it is one of your other routes matching your request, and so that is why you are not seeing your console.log either. It's not even hitting this route.

9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.