skip to Main Content
function getDigitalMigrationJoin(req, res, next) {
    DigitalMigrationForm.aggregate([
        // Join with user_info table
        {
            $lookup: {
                from: DigitalMigrationFormList.collection.name,       // other table name
                localField: "_id",   // name of users table field
                foreignField: "digitalFormId", // name of userinfo table field
                as: "forms"         // alias for userinfo table
            }
        },

    ]).exec(function (err, results) {
        console.log(results)
        res.send(results)

    })

}

i want to add pa gination on this function with limit and page please help me

2

Answers


  1. To add pagination, you cam use the $skip and $limit within the aggregate method.

    $skip skips a specific number of documents; $limit limits the number of documents passed to the next stage in the pipeline.

    He is an updated version of your function:

    const getDigitalMigrationJoin = (req, res, next) => {
        // Extract page and pageSize parameters from the request query
        const page = req.query.page || 1;
        const pageSize = req.query.pageSize || 10;
    
        // Calculate skip and limit values based on the page and pageSize
        const skip = (page - 1) * pageSize;
        const limit = pageSize;
    
        DigitalMigrationForm.aggregate([
            // Join with user_info table
            {
                $lookup: {
                    from: DigitalMigrationFormList.collection.name,       // other table name
                    localField: "_id",   // name of users table field
                    foreignField: "digitalFormId", // name of userinfo table field
                    as: "forms"         // alias for userinfo table
                }
            },
            // Skip a specified number of documents
            { $skip: skip },
            // Limit the number of documents passed to the next stage
            { $limit: limit }
        ]).exec(function (err, results) {
            console.log(results)
            res.send(results)
        })
    }
    
    Login or Signup to reply.
  2. You can do it like this:

    const page = req.query.page || 1;
    const pageSize = req.query.pageSize || 10;
    
    DigitalMigrationForm.aggregate([
      {
        $lookup: {
          from: DigitalMigrationFormList.collection.name,      
          localField: "_id",  
          foreignField: "digitalFormId", 
          as: "forms",
        }
      },
      {
        $facet: {
          metadata: [{ $count: 'totalRecords' }],
          data: [{ $skip: (page - 1) * pageSize }, { $limit: pageSize }],
        },
      },
    ])
    

    Note the use of $facet stage, that allows us to return both the total records count, as well as all the document for requested page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search