Open dipendrasingh100 opened 11 months ago
Hii, I think I can help you. The error "Query was already executed" in Mongoose occurs because you're trying to execute the same query object more than once. To fix this, you need to clone the query object before reusing it. You can use the query clone method provided by Mongoose to clone the query and execute it again.
`exports.getAllProducts = catchAsyncErrors(async (req, res, next) => { const resultPerPage = 8; const productsCount = await Product.countDocuments();
const apiFeature = new ApiFeatures(Product.find(), req.query) .search() .filter();
let products = await apiFeature.query.clone();
let filteredProductsCount = products.length;
// Clone the query again for pagination apiFeature.pagination(resultPerPage);
products = await apiFeature.query.clone();
res.status(200).json({ success: true, products, productsCount, resultPerPage, filteredProductsCount, }); }); `
In the backend>controller>productController.js getAllProducts() throwing the error- "Query was already executed"
Mongoose no longer allows executing the same query object twice. If you do, you'll get a Query was already executed error. Executing the same query instance twice is typically indicative of mixing callbacks and promises, but if you need to execute the same query twice, you can call Query#clone() to clone the query and re-execute it.