我正在从我的前端获取API请求,因为我使用reactjs当我尝试按价格过滤产品时,我得到了意想不到的错误:
axios叫
axios.get(`/api/v1/products?keyword=${keyword}&page=${currentPage}&price[lte]=${price[1]}&price[gte]=${price[0]}`)
后端>在我的后端,我正在处理get请求
exports.getProducts = (req, res, next) => {
const resPerPage = 4;
const productsCount = await Product.countDocuments();
const apiFeatures = new APIFeatures(Product.find(), req.query)
.search()
.filter();
let products = await apiFeatures.query;
let filteredProductsCount = products.length;
apiFeatures.pagination(resPerPage);
products = await apiFeatures.query;
res.status(200).json({
success: true,
productsCount,
resPerPage,
filteredProductsCount,
products,
});
};
和我的APIFeatures.js是
class APIFeatures {
constructor(query, queryStr) {
this.query = query;
this.queryStr = queryStr;
}
search() {
const keyword = this.queryStr.keyword
? {
name: {
$regex: this.queryStr.keyword,
$options: 'i',
},
}
: {};
this.query = this.query.find({ ...keyword });
return this;
}
filter() {
const queryCopy = { ...this.queryStr };
// removing fields from the query
const removeFields = ['keyword', 'limit', 'page'];
removeFields.forEach((el) => delete queryCopy[el]);
// advance filter for price, ratings etc
let queryStr = JSON.stringify(queryCopy);
queryStr = queryStr.replace(/b(gt|gte|lt|lte)b/g, (match) => `$${match}`);
this.query = this.query.find(JSON.parse(queryStr));
return this;
}
pagination(resPerPage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resPerPage * (currentPage - 1);
this.query = this.query.limit(resPerPage).skip(skip);
return this;
}
}
module.exports = APIFeatures;
但是当我从我的前端调度get请求时,我得到关于我的价格过滤器的错误
误差
"Query was already executed: Product.find({ price: { '$lte': 1000, '$gte': 1 } })"
https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution
products = await apiFeatures.query.clone();
我也面临同样的问题一个快速解决这个问题的方法是在再次执行查询时使用clone。
: -
products = await apiFeature.query.clone();
使用
const apiFeatures = new APIFeatures(Product.find().exec(), req.query)
.search()
.filter();
这对我有用
let products = await apiFeatures.query.clone();
当给定的查询被执行两次时,Mongoose抛出'Query was already executed'错误。最常见的解释是你混合了await和回调。
你可以简单地创建类Apifeature的一个虚拟实例,不使用分页,找到filteredProductsCount,然后创建类Apifeature的另一个实例,并对其使用分页。
exports.getAllProducts = catchAsyncError(async (req, res, next) => {
const resultperpage = 8;
const productcount = await Product.countDocuments();
const apifeaturesdemo = new ApiFeatures(Product.find(), req.query)
.search()
.filter();
let products = aenter code herewait apifeaturesdemo.query;
let filteredProductsCount = products.length;
// apifeatures.pagination(resultperpage);
const apifeatures = new ApiFeatures(Product.find(), req.query)
.search()
.filter()
.pagination(resultperpage);
products = await apifeatures.query;
if (!products) {
return next(new ErrorHandler("Product not found", 404));
}
res.status(200).json({
success: true,
products,
productcount,
resultperpage,
filteredProductsCount,
});
});
我也面临这个问题。因此,编写下面的代码来解决这个问题。
products = await apiFeatures.query.clone();