I have got this error:
MongoServerError: Skip value must be non-negative, but received: -9223372036854775808
router request:
router.post("/products/by/search", listBySearch);
listBySearch
method in product controller:
exports.listBySearch = (req, res) => {
let order = req.body.order ? req.body.order : "desc";
let sortBy = req.body.sortBy ? req.body.sortBy : "_id";
let limit = req.body.limit ? parseInt(req.body.limit) : 100;
let skip = parseInt(req.body.skip);
let findArgs = {};
// console.log(order, sortBy, limit, skip, req.body.filters);
// console.log("findArgs", findArgs);
for (let key in req.body.filters) {
if (req.body.filters[key].length > 0) {
if (key === "price") {
// gte - greater than price [0-10]
// lte - less than
findArgs[key] = {
$gte: req.body.filters[key][0],
$lte: req.body.filters[key][1]
};
} else {
findArgs[key] = req.body.filters[key];
}
}
}
Product.find(findArgs)
.select("-photo")
.populate("category")
.sort([
[sortBy, order]
])
.skip(skip)
.limit(limit)
.exec((err, data) => {
if (err) {
console.log(err);
return res.status(400).json({
error: "Products not found"
});
}
res.json({
size: data.length,
data
});
});
};
CodePudding user response:
As you state in your comments, the issue occurs when there's no value for skip
passed in req.body
, which means skip = parseInt(undefined)
, which is NaN
.
Instead, try setting a default skip value of 0:
let skip = parseInt(req.body.skip) || 0;