Mongodb query by id when id is null

I am creating a search functionality to search by a few fields, one of which being the id of the document in the collection. When the id is not filled out I am getting the error "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters" as expected since it is trying to convert a blank string to an id. I have tried adding it into the query conditionally but I keep getting errors. Here is the basic idea of the query:

{
  $or: [ { name: {$regex: '/*{{companyName.value}}*', $options: 'i'} },
        { _id: 
          { "$oid": '{{companyId.value  ? companyId.value : '' }}' }
        }
                  
                  
      ]
}

How can I ensure that the section of the query for the id is only run if the user adds an id to the appropriate field?

Hey @Chris_Bartlett!

I think you are on the right track, but instead of conditionally sending the value, you'd want to conditionally want to send a different object. Created a simple example here based off of a switch value.

Switch has a value, send the query with the email param => receive 4 items

Switch doesn't have a value, send an empty query object => receive 53 items

Let me know if you get that working!

That worked, thanks!

1 Like