Home > other >  How to add pagination with all page details in node js and mongodb
How to add pagination with all page details in node js and mongodb

Time:11-15

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.

CodePudding user response:

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 })
  }
})

  • Related