'"unexpected identifier error" in pagination function
although I passed the model variable in the parameters, it doesn't read them and gives a syntax error of unexpected identifier...
what is the issue ....any insight is much appreciated
function paginatedResults(model) {
return (req, res, next) => {
const page = parseInt(req.query.page);
const limit = 20;
const startIndex = (page - 1) * limit;
const endIndex = page * limit;
const results = {};
if (endIndex < await model.countDocuments().exec()) {
results.next = {
page: page + 1,
limit: limit,
};
}
if (startIndex > 0) {
results.previous = {
page: page - 1,
limit: limit,
};
}
try {
results.results =await model.find().limit(limit).skip(startIndex).exec();
res.paginatedResults = results;
next();
}
catch (error) {
res.status(400).json({message:error})
}
};
}
module.exports=paginatedResults
Solution 1:[1]
Add async at the start of the function call
Solution 2:[2]
The problem may be async await
I have the same error
storeCtrl.getStores = async paginatedResults(Store), (req, res) => {
try {
res.json(res.paginatedResults);
} catch (e) {
res.status(400).send("Bad request");
}
};
If you look carefully there is an async coming to the function, for some reason if I remove async everything works fine... so my point is that it can't just be an async problem, maybe it's because a function is being called after having entered a property, parameter, attribute, etc before.
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 | The Golden Dev |
Solution 2 |