Implement Pagination in MongoDB

Update the getAllUsers service to accept pagination options.

We will use Promise.all() to execute the record query and count query concurrently.

The count query determines how many matching documents exist, while the find query retrieves the requested page.

Paginated User Service
export async function getUsers({ page, limit }) {
  const skip = (page - 1) * limit;

  const [users, total] = await Promise.all([
    User.find()
      .select('-password')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit),
    User.countDocuments()
  ]);

  return {
    users,
    total,
    page,
    limit,
    totalPages: Math.ceil(total / limit)
  };
}

Retrieves a page of users and the total number of matching records concurrently.

Key Takeaways
  • skip() applies the pagination offset.

  • limit() restricts the number of returned documents.

  • countDocuments() provides the total record count.