I created a simple API to fetch a list of data from MongoDB. I also added the pagination in case the document grows to manage the data in multiple data throughout pages. However, I am facing the issue of document skipping when I use the pageSize
value to 2 or 3 (but it works on 5 currently have 7 documents in total) in the list it only skips one document when I go through the one-by-one pages I see that some of the documents are not showing in the list. Here is the code. Please comment if you need more info.
export const getSchemesList = expressAsyncHandler(async (req, res) => {
try {
const { pageSize, pageNumber, status } = req.query;
const page = Number(pageNumber) || 1;
const sort = { created_at: -1 };
let query = {};
if (status) {
query.status = status;
}
const count = await Scheme.countDocuments(query);
const skipDoc = pageSize * (page - 1);
const pages = Math.ceil(count / pageSize);
let schemes;
if (status) {
schemes = await Scheme.find(query).sort(sort).limit(pageSize).skip(skipDoc);
} else {
schemes = await Scheme.find().sort(sort).limit(pageSize).skip(skipDoc);
}
res.json({ schemes, page, pages });
} catch (error) {
res.status(500);
throw new Error({ message: "Internal Server Error" });
}
});
I found the problem or the bug with the help of @bvdb and @OnurDoğan. The problem is with my sorting const sort = { created_at: -1 };
I used this line to sort my response data but the issue is I never added the timestamp
field in the schema so there is no variable called createdAt
.