2nd way to get count >>>>>>>>>>>>
const getPosts = async (req, res) => {
const { filter, pageNumber = 1, pageSize = 10 } = req.query;
try {
// Convert pageNumber and pageSize to integers
const page = parseInt(pageNumber);
const limit = parseInt(pageSize);
const skip = (page - 1) * limit;
// Match content using regex for partial matching if a filter is provided
const matchStage = filter
? { content: { $regex: filter, $options: 'i' } }
: {};
// Get total document count with filter
// const totalDocuments = await Post.countDocuments(matchStage);
// Get Posts with the filter, pagination, and user details
const result = await Post.aggregate([
{
$match: matchStage // Match stage to filter posts
},
{
$facet: {
totalCount: [
{ $count: "totalDocuments" } // Count total matching documents
],
paginatedData: [
{ $sort: { createdAt: -1 } }, // Sort posts by creation date
{ $skip: skip }, // Skip for pagination
{ $limit: limit }, // Limit for pagination
{
$lookup: {
from: 'users',
localField: 'user_id',