'While testing API containing pagination in postman facing skip value error
I am using pagination middleware in my node js project but while testing api in postman it's throwing error skip value
Followed the paginate docs but still no use
below is my pagination middleware
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 });
}
};
};
Solution 1:[1]
If page
is not provided in the query, it will end up being NaN
, since this code does not cover that case:
// 'req.query.page' is undefined
let page = parseInt(req.query.page);
if (page < 1 || page == undefined) {
page = 1;
}
// 'page' is now equal to NaN
A correct way to handle this could be:
let page = parseInt(req.query.page);
if (page < 1 || isNaN(page)) {
page = 1;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | madzong |