我想根据查询的产品类型为我的产品列表添加过滤。
假设我想实现这个:
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"]
}
所以按照@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
}
}