meabhisingh / mernProjectEcommerce

This is MERN Stack Ecommerce Project Made to Teach MERN Stack on YouTube
1.15k stars 828 forks source link

🚨MongooseError: Query was already executed #77

Open dipendrasingh100 opened 11 months ago

dipendrasingh100 commented 11 months ago

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.

Santosh130602 commented 2 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, }); }); `