简体   繁体   English

在 MongoDB 中有条件地申请和条件

[英]Conditionally apply and condition in MongoDB

I am trying to fetch data conditionally based on parameter passed.我试图根据传递的参数有条件地获取数据。

Parameters are 'room' and 'area'参数是“房间”和“区域”

if room is not equal to 'any', I want to add condition in filter for room.如果房间不等于“任何”,我想在房间的过滤器中添加条件。
if area is not equal to 'all', I want to add condition in filter for area.如果面积不等于“全部”,我想在面积过滤器中添加条件。

exports.get_property_search = function (req, res) {
    var filter = [];
    if (req.params.area != "all")
        filter.push({ "area": req.params.area });
    if (req.params.room != "any")
        filter.push({ "roomQty": req.params.room });

    AddProperty.find({
        $expr:
        {
            $cond:
            {
                if: filter != [],
                then: {
                    $and: filter
                },
                else: {

                }
            }
        }
    }, function (err, addProperty) {
        if (err)
            res.send({ code: '500', message: err });
        res.send({ code: '200', data: addProperty });
    });
};

But, this condition is not working and all returning all the data without any filter.但是,这种情况不起作用,并且所有数据都返回了没有任何过滤器的所有数据。

You are going with the wrong syntax here.你在这里使用错误的语法。 And this can be done using simple javascript code instead of using aggregation operator.这可以使用简单的 javascript 代码而不是使用聚合运算符来完成。

let filter = {}
  if (req.params.area !== "all") {
    filter.area = req.params.area
  }
  if (req.params.room !== "any") {
    filter.roomQty = req.params.room
  }

  AddProperty.find(filter).then((data) => {
    console.log(data)
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM