skip to Main Content

I am trying to find 3 different field values while searching with .find() method and it gives either complete data or only one.

This is the code I have given:

const search = req.query.search || "";

const Rest = await Restaurant.find(
                                   {name:{$regex:search,$options:"i"}},
                                   {locality:{$regex:search,$options:'i'}},
                                   {"cuisine.name":{$regex:search,$options:'i'})

I am getting an empty array as output, as I mentioned multiple fields together in .find()..

I am getting output if I use the below code(i.e) find only one field..

const Rest = await Restaurant.find({name:{$regex:search,$options:"i"}})

If I search for any of the 3 fields name/locality/cuisine.name I should get appropriate output.

2

Answers


  1. Your original query was incorrect. Those conditions should be grouped into one parameter. It should be as below:

    const Rest = await Restaurant.find({
      name: {
        $regex: search,
        $options: "i"
      },
      locality: {
        $regex: search,
        $options: "i"
      },
      "cuisine.name": {
        $regex: search,
        $options: "i"
      }
    })
    

    The above query will work the matching in AND conditions (all filter criteria must be fulfilled).

    Instead, you need to work the query in OR conditions with the $or operator (either one of the filter criteria needed to be fulfilled).

    Solution

    const Rest = await Restaurant.find({
      $or: [
        {
          name: {
            $regex: search,
            $options: "i"
          }
        },
        {
          locality: {
            $regex: search,
            $options: "i"
          }
        },
        {
          "cuisine.name": {
            $regex: search,
            $options: "i"
          }
        }
      ]
    })
    

    Demo @ Mongo Playground

    Login or Signup to reply.
  2. You can look at $and operator and $or operator in Mongodb, You can use $and operator if you want to match all of the given parameters or $or operator if one must match. Like this:

    const Rest = await Restaurant.find({
      $and: [
        { name: { $regex: search, $options: "i" } },
        { locality: { $regex: search, $options: "i" } },
        { "cuisine.name": { $regex: search, $options: "i" } },
      ],
    });
    

    See the documentation:

    $and operator

    $or operator

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search