在邮递员中测试包含分页的 API 时面临跳过值错误

While testing API containing pagination in postman facing skip value error

我在我的节点 js 项目中使用分页中间件,但是在邮递员中测试 api 时它抛出错误跳过值

遵循分页文档,但仍然没有用

下面是我的分页中间件

    const pagination = (model) => {
  return async (req, res, next) => {
    const limit = parseInt(req.query.limit);
    const page = parseInt(req.query.page);

    if (page < 1 || page == undefined) {
      page = 1;
    }
    if (limit < 1 || limit == undefined) {
      limit = 2;
    }
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const result = {};
    model.countDocuments({}, (err, count) => {
      const lengthOfDB = count;
      if (endIndex < lengthOfDB) {
        result.next = {
          page: page + 1,
          //limit: limit,
        };
      }
    }).clone();

    if (startIndex > 0) {
      result.previous = {
        page: page - 1,
        //limit: limit,
      };
    }
    try {
      result.result = await model.find().limit(limit).skip(startIndex).exec();
      res.json(result);
    } catch (e) {
      res.status(500).json({ message: e.message });
    }
  };
};

如果查询中未提供 page,它将最终成为 NaN,因为此代码不涵盖这种情况:

// 'req.query.page' is undefined
let page = parseInt(req.query.page);
if (page < 1 || page == undefined) {
    page = 1;
}
// 'page' is now equal to NaN

处理此问题的正确方法可能是:

let page = parseInt(req.query.page);
if (page < 1 || isNaN(page)) {
    page = 1;
}