简体   繁体   中英

server side pagination in node js and mongo db

please help me with this server side pagination in node.js and mongo db

function getServiceQualityAnex(req, res, next) {
    if (req.query.code != null) {
        ServiceQualityAnex.find({ location: req.query.code }).sort({ _id: -1 }).select('-hash')
            .then(serviceQualityAnexC => res.json(serviceQualityAnexC))
            .catch(err => {
                res.sendStatus(404);
                next(err)
            });
    } else {
        ServiceQualityAnex.find({}).sort({ _id: -1 }).select('-hash')
            .then(serviceQualityAnexC => res.json(serviceQualityAnexC))
            .catch(err => {
                res.sendStatus(404);
                next(err)
            });
    }
}

i want to do a server side pagination on server side my front end api is http://localhost:3000/getServiceQualityAnexJoin/ the function which is mentioned above is combing 2 tables are returning. my data is very huge and i want to add a server side pagination

You did not specify all the requirements in your question but what i precieve is that you want to do pagination on server side with nodejs in mongodb Here is what you need to do:

const getServiceQualityAnex = async (request, response) => {
try {
    const id = request.params.id;

    let { page } = request.query; //this indicates the page you are requesting for in pagination

    if (!page)
        page = 1; //by default it is one

    const result = await ServiceQualityAnex.aggregate([
        {
            $match: {
                "_id": mongoose.Types.ObjectId(id)
            }
        },
        {
            $project: {
                "_id": 1,
                .
                .
                .
                // all the fields you want to get

            }
        },
        {
            $facet: { //facet is the aggregation pipeline in mongodb through which you can achieve pagination 
                metadata: [{ $count: 'total' }],
                data: [
                    {
                        $skip: (Number(page) - 1) * Number(20)
                    },
                    {
                        $limit: 20 //20 records limit per page
                    },
                ]
            }
        }
    ]);
    console.log("result :", result[0].data);

    return response
        .status(200)
        .json(
            {
                result: result[0].data,
                meta: {
                    current_page: page,
                    total_pages: Math.ceil(
                        (Number(result[0].metadata.length === 0 ? 0 : result[0].metadata[0].total))
                        / (Number(20))),
                    total_count: result[0].metadata.length === 0 ? 0 : result[0].metadata[0].total,
                }
            }
        );
} catch (error) {
    console.log(error);
    response.status(500).json({
        error: "Something went wrong",
    });
  }
}

If you don't know anything about aggregation then you must visit this site: MongoDB aggregation framework

let page = Number(req.query.page);
page = page ? page : 0;
let limit = parseInt(req.query.limit);
const result = {};
let startIndex = page * limit;
if (startIndex > 0) {
  result.previous = {
    page: page - 1,
    limit: limit,
  };
}

let receive = await Model.find()
  .sort("-_id")
  .skip(startIndex)
  .limit(limit)
  .exec();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM