簡體   English   中英

node.js 和 mongo db 中的服務器端分頁

[英]server side pagination in node js and mongo db

請幫助我在 node.js 和 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)
            });
    }
}

我想在服務器端進行服務器端分頁,我的前端 api 是 http://localhost:3000/getServiceQualityAnexJoin/ 上面提到的函數正在返回 2 個表。 我的數據非常龐大,我想添加服務器端分頁

你沒有在你的問題中指定所有要求,但我知道你想在 mongodb 中使用 nodejs 在服務器端進行分頁這是你需要做的:

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",
    });
  }
}

如果你對聚合一無所知那么你必須訪問這個網站: MongoDB聚合框架

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM