【问题标题】:MongoDB passing query from requestMongoDB 从请求中传递查询
【发布时间】:2021-05-24 05:35:14
【问题描述】:

我想通过查询中的产品类型将过滤添加到我的产品列表中。

假设我想实现这个:

Product.find({
   "product_type.name": {
     $in: ["A", "B"]
   }
})

过滤我的产品类型为“A”或“B”。但我并不总是想过滤,这就是为什么从请求中我看到我们是否有这个过滤。所以我检查如下:

let query = {}
if (req.query.product_type) {
    query.product_type.name =  {
     $in: ["A", "B"]
   }
}

product_type = ["A", "B"] 来自请求。

然后:

Product.find(query)

当我运行它时,我得到了错误

TypeError: Cannot set property 'name' of undefined.

我希望查询值像

   "product_type.name": {
     $in: ["A", "B"]
   }

【问题讨论】:

  • query["product_type.name"]

标签: javascript mongodb mongoose mongodb-query


【解决方案1】:

按照@willis 的建议,请执行以下操作

let query = {};

if (Array.isArray(req.query.product_type) && req.query.product_type.length > 0) {
    query["product_type.name"] =  {
        $in: req.query.product_type
    }
}

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2012-08-28
    • 2012-01-13
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多