im trying to split my products into many pages of 5 products , so the user can't face fetching all the products at once ! it worked , but while i was trying to get the length of the products so i can know how much pages i should display in the frontend i couldn't just get the length before splitting it keeps telling const err = new MongooseError('Query was already executed: ' + str); so i fetched the products another time and just got the length from it ! is that bad ? i mean will that somehow effect the experience because im fetching twice ? any other solutions that can be good for user experience
router.get(`/`, async (req, res) => {
let filter = {};
if (req.query.categories) {
filter = { category: req.query.categories.split(",") };
}
let result = Product.find(filter).populate("category");
let lengthSearch = Product.find(filter);
const length = (await lengthSearch).length;
if (!result) {
res.status(500).json({ success: false });
}
const limit = Number(req.query.limit) || 5;
if (req.query.viewmore) {
result = result.limit(limit * Number(req.query.viewmore));
} else {
const page = Number(req.query.page) || 1;
const skip = (page - 1) * limit;
result = result.skip(skip).limit(limit);
}
const productList = await result;
res.send({ length, products: productList });
});