"Pagination Api Structure in Node js"
Bootstrap 4.1.1 Snippet by Arjunverma

1
2
3
4
5
6
7
8
9
10
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="row">
<h2>Pagination Api Structure</h2>
</div>
</div>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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',
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
1st 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 posts = await Post.aggregate([
{
$match: matchStage
},
{
$lookup: {
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'users'
}
},
{
$unwind: {
path: '$users',
preserveNullAndEmptyArrays: true
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Related: See More


Questions / Comments: