简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM