0

I'm trying to build a filter where it should be possible to query all items selected in an array, but also to show documents where the property has not been set.

returning all specific from an array works fine with below

 searchCriteria.filter1 = {
          $in: array.category,
        };
 searchCriteria.filter2 = {
          $in: array.carbrand,
        };

//Then the data if fetched 
 const fetchedData = await Activity.find(searchCriteria)
      .sort({ date: -1 })
      .limit(limit)
      .skip(startIndex)
      .exec();

However, sometimes users have not added a category, and it's just a empty array. My goal is to get all of these empty arrays as well as the specific arrays.

so something like:

searchCriteria.filter2 = {
         $in: array.carbrand OR is []
       };

Any suggestions?

1 Answer 1

1

One way you could approach this is indeed to use the $or operator. But since $in is logically an OR for a single value, you should be able to just append [] to the list being used for comparison by the $in operator.

The approach is demonstrated in this playground example.

I believe you could adjust the code in a manner similar to this:

 searchCriteria.filter2 = {
          $in:  [...array.carbrand, []]
        };
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This works great. I was stuck on the "OR" function - but this solution works great also when having multiple filters which all need this functionality, at the same time. :-)
Excellent! For general reference, the alternative syntax would be something like $or: [{filter2:{$in:array.carbrand}}, {filter2:[]}] }. But the documentation itself recommends $in over $or for situations like this anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.