I am using Mongoose paginate with search and filter queries for a schema called Thought. In my thought index .ejs template, I am displaying 40 records on each page using a forEach loop:
<% thoughts.docs.forEach(function(thought, i) { %>
There is a Show More button to click for the next 40 records:
<div id="box-show-more" >
<button id="showMoreBtn" data-page="<%= thoughts.page 1 %>">Show More</button>
</div>
When a search/filter is applied on the author of the record, many of the authors have less than 40 records, but currently, the Show More button is still displayed. In my controller, the pagination is defined like this:
const thoughts = await Thought.paginate(queryObject, {
page: req.query.page || 1,
limit: 40,
sort: { 'createdAt': -1},
populate: 'likes',
collation: { locale: "en" }
});
I want to include a count of the total documents, so I can add a wrapper around the Show More button like, 'if more than 40 records, display Show More button'. But I'm unsure how to include a count in the pagination query. In Mongoose docs a can see there is a field called 'totalDocs', but I'm unsure where to include this or how to return the value from it and use in my .ejs template.
CodePudding user response:
Not sure which library/plugin for mongoose-pagination you are using, but considering this library it should be fairly straight-forward:
const result = await Thought.paginate(queryObject, {
page: req.query.page || 1,
limit: 40,
populate: 'likes'
});
console.log(result.totalDocs);
The object returned from the paginate
call will contain a property totalDocs
which yields the total number of documents in collection that match your query.