axios 为什么我得到这个错误?“查询已执行:产品.查找({价格:{“$lte”:1000,“$gte”:1 } })”

iovurdzv  于 2023-03-02  发布在  iOS
关注(0)|答案(5)|浏览(82)

当我使用reactjs时,我从前端获取API请求当我尝试按价格过滤产品时,我收到意外错误:

    • 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,
  });
};

我的APIFatures.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;

但是当我从我的前端调度得到请求时,我得到了关于我的价格过滤器的错误

    • 错误**
"Query was already executed: Product.find({ price: { '$lte': 1000, '$gte': 1 } })"
ioekq8ef

ioekq8ef1#

https://mongoosejs.com/docs/migrating_to_6.html#duplicate-query-execution

products = await apiFeatures.query.clone();
xkftehaa

xkftehaa2#

嘿,我也遇到了同样的问题,一个快速的解决方法是在再次执行查询时使用clone。
就像这样:

products = await apiFeature.query.clone();
cu6pst1q

cu6pst1q3#

用这个

const apiFeatures = new APIFeatures(Product.find().exec(), req.query)
    .search()
    .filter();
7xzttuei

7xzttuei4#

这对我很有效

let products = await apiFeatures.query.clone();
vom3gejh

vom3gejh5#

当一个给定的查询被执行两次时,Mongoose会抛出一个“Query was already executed”错误。最常见的解释是你把等待和回调混在了一起。

相关问题