简体   繁体   中英

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.

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)
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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