Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
How to add pagination with all page details in node js and mongodb

HI I have to add pagination in NodeJS and MongoDB I have done this code

router.get("/PO_pagination", verify, async (req, res) => {
  console.log("req.query", req.query)
  try {
    let { page, size } = req.query
    if (!page) {
      page = 1
    }
    if (!size) {
      size = 10
    }
    const limit = parseInt(size)
    const skip = (page - 1) * size

    const po = await PurchaseOrders.find().limit(limit).skip(skip)
    return res.send({
      page: page,
      size: size,
      data: po
    })
  } catch (error) {
    console.log("error", error)
    return res.status(400).json({ error: error })
  }
})

I am getting data according to req.query but I also want to return the total number of pages on the basis of limit and skip getting from the query like if I said page=1&limit=200 so it arrange a total number of pages according to query params. Also, I want to add the next and prev in res. Like how many pages are next and how many pages are in prev.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use countDocuments() to get total number of documents, and then you can calculate your requested data.

router.get("/PO_pagination", verify, async (req, res) => {
  console.log("req.query", req.query)
  try {
    let { page, size } = req.query
    if (!page) page = 1;
    if (!size) size = 10;
    const limit = parseInt(size)
    const skip = (page - 1) * size

    const po = await PurchaseOrders.find().limit(limit).skip(skip);
    const total_documents = await PurchaseOrders.countDocuments();
    
    const previous_pages = page - 1;
    const next_pages = Math.ceil((total_documents-skip)/size);
  
    return res.send({
      page: page,
      size: size,
      data: po,
      previous: previous_pages,
      next: next_pages 
    })
  } catch (error) {
    console.log("error", error)
    return res.status(400).json({ error: error })
  }
})

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!