Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda