0

I will have to sort data by data and acccording to the pagination. This is the query which I used response.data = await distributorDoc.find().sort({"TimeStamp":-1,}); It is the pagination pagination: { totalCount: 0, pageCount: 0, currentPage: page, perPage: reqData.perPage || perPageCount }

response.data = await distributorDoc.find().sort({"TimeStamp":-1,"perpage"==100});

2 Answers2

1

You could try with limit and skip methods from MongoDB.

The limit() function in MongoDB is used to specify the maximum number of results to be returned

If you want to get certain number of results after some documents, you could use skip() function.

Sample Node JS code for pagination:

    function fetchDocs(pageNumber, nPerPage) {
        console.log('Page: ' + pageNumber);
        distributorDoc.find()
          .sort({'TimeStamp': -1})
          .skip(pageNumber > 0 ? ((pageNumber - 1) * nPerPage) : 0)
          .limit(nPerPage)
          .forEach(doc => {
              console.log(doc);
          });
     }

Read more about them here

limit()

skip()

Checkout this link for other alternatives

Hope this is what you're looking for.

vidyasagar
  • 31
  • 2
1

Here's an example of how you can do it assuming you have the following variables:

page: The current page number.
perPage: The number of items you want to show per page.
distributorDoc: The Mongoose model for your distributor document.

// Set the page and perPage variables based on the request data or use the default values.
const page = reqData.page || 1;
const perPage = reqData.perPage || perPageCount;

// Calculate the totalCount using the countDocuments() method.
const totalCount = await distributorDoc.countDocuments();

// Calculate the pageCount by dividing the totalCount by perPage and rounding up.
const pageCount = Math.ceil(totalCount / perPage);

// Calculate the skipItems to determine how many items to skip based on the current page number.
const skipItems = (page - 1) * perPage;

// Modify the query to include .skip(skipItems) and .limit(perPage) for implementing pagination.
response.data = await distributorDoc.find()
  .sort({ "TimeStamp": -1 })
  .skip(skipItems)
  .limit(perPage);

// Update the response.pagination object with the new values.
response.pagination = {
  totalCount: totalCount,
  pageCount: pageCount,
  currentPage: page,
  perPage: perPage
};
andrewoodleyjr
  • 2,971
  • 2
  • 21
  • 21