react – $regex search for two separate keys in MongooseDB object, can only access one at a time

const keyword = req.query.keyword
        ? {
                name: {
                    $regex: req.query.keyword,
                    $options: "i",
                },
          } && {
                category: {
                    $regex: req.query.keyword,
                    $options: "i",
                },
          }
        : {};

    const products = await Product.find({ ...keyword })

In my react app, I’m using a search bar component which makes DB queries based on a keyword (in the above example, ‘category’ and ‘name’ are both keys in a MongoDB model). With the above, I can only access the second on the list, i.e. ‘category’. Bizarrely this worked fine with the above syntax until this morning, so I don’t know what I’ve changed. The only other file I’ve changed is .css so I doubt there’s anything at fault there.

Is there a way to access both at once?

Thanks in advance

Answer

The issue is you’re using && on objects which are truthy causing the second expression to be returned.

From the Logical AND docs,

expr1 && expr2

If expr1 can be converted to true, returns expr2; else, returns expr1.

You should be using the $or operator to query on name or category fields.

const keyword = req.query.keyword
  ? {
      $or: [
        {
          name: {
            $regex: req.query.keyword,
            $options: 'i',
          },
        },
        {
          category: {
            $regex: req.query.keyword,
            $options: 'i',
          },
        },
      ],
    }
  : {}

Leave a Reply

Your email address will not be published. Required fields are marked *