【问题标题】:Building a product-filter in NodeJS/MongoDB: only works when selecting all filters在 NodeJS/MongoDB 中构建产品过滤器:仅在选择所有过滤器时有效
【发布时间】:2021-05-26 23:49:35
【问题描述】:

我正在 nodeJS 中构建产品过滤器。当我 硬编码 以下 find()

 const products = await Product.find({
            price: {
              $gte: price[0],
              $lte: price[1],
            }, category: categories, shipping: shipping})

问题当然是只有在前端输入所有搜索选项时才会给出结果。 但是,如果我选择 不 输入所有搜索选项,我也希望过滤器能够正常工作。 因此,我想出了以下代码,将所有过滤器存储在一个数组中,但它没有给出任何结果。 数组的输出是=

  { price: { '$gte': 0, '$lte': 40820 } },
  {
    category: [
      '60657e1d328b25043581e46f',
      '601ef1ea8e06fc04cdaa5080',
      '601eeaeb8e06fc04cdaa507f'
    ]
  },
  { shipping: 'Yes' }
] <<<_--- content of searchArry????

这是我的代码,但它没有返回任何结果 =

exports.searchFilters = async (req, res) => {
  try {
  const categories = req.body.categoryIds;
  const price = req.body.price; 
  const shipping = req.body.shipping;
  console.log(price, "<<<------- price data received in backend???"); 
  console.log(categories, "<<--- categories data received in backend???"); 
  console.log(shipping, "<<---- shipping data received in backend"); 
  
  const searchArray = [];
 
  if (req.body.price) {
    const price = {
      $gte: req.body.price[0],
      $lte: req.body.price[1],
    }
    searchArray.push({ "price" : price });
  }

  if (req.body.categoryIds) {
    

    searchArray.push({ "category" : categories });
  }

  if (req.body.shipping) {
    
    searchArray.push({ "shipping" : shipping });
  }

        console.log(searchArray, "<<<_--- content of searchArry????");

  const products = await Product.find({searchArray})
  .populate("category", "_id name") 
  .populate("subs", "_id name") 
  .populate("postedBy", "_id name") 
  .exec(); 
  
  res.json(products);
  // console.log(products, "<<--producte?? ") console.log(products.length, "<<--- lengte") } catch(err) { console.log(err); }}
  } catch(err) {
    console.log(err);
  }
}

【问题讨论】:

    标签: node.js reactjs mongodb


    【解决方案1】:

    您的硬编码调用如下所示:

    Product.find({price, category, shipping}) // the arg is an object
    

    第二个电话(searchArray)看起来像:

    Product.find({searchArray: [{price}, {category}, {shipping}]}) // the arg is an object containing an array of objects
    

    尝试将searchArray 的元素合并到一个对象中:

    Product.find(Object.assign({}, ...searchArray))
    

    注意:请注意,{variableName} 是 {variableName: variableName} 或 {"variableName": variableName} 的简写。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 2016-10-16
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      相关资源
      最近更新 更多