'Filter inside the fetch with mongoDB query operators

how are you? I'm trying to move a filter inside the fetch I'm doing to bring my data from Builder.io and I'm struggling with one of them here. The title search works fine, but the second one don't. My objective is to filter between the entries to catch only the ones that match at least one of the annotationArray items. The annotationArray can be, for example:

const annotationArray = ['Video', 'Image', 'GPS'] 

or just

const annotationArray = ['Video'] 

or whatever.

And the entries have an annotation field that consists in a string where I pass the annotations, like this:

const entries = [{title: 'First', annotation: 'Video, GPS'}, {title: 'Second', annotation: 'GPS'}, {title: 'Third', annotation: 'Video, Image'}]

So, for example, if the annotationArray is ['Video', 'GPS'], I want to fetch all of them. But if it's ['Video'], only the third and first, and so.

Currently I have this code

    const sets = await builder.getAll('open-dataset', {
      options: { noTargeting: true },
      omit: 'data.blocks',
      limit: 100,
      query: {
        data: {
          title: { $regex: search, $options: 'i' },
          annotation: { $regex: annotationArray && annotationArray.join(' '), $options: 'i' },
        }
      }
    });

The result of annotationArray.join(' ') can be, for example, Video Image GPS or just Image. And annotation Video Image or whatever.

So I need to filter between the entries and fetch only the ones that contain at least one of the annotationArray strings.

My code is failing because currently it only fetches the ones that have all the annotationArray items, and not the ones that have at least one. I don't know how to do it with MondoDB query operators... previously, I had this code with javascript and it worked fine.

const filtered = entries.filter(item => annotationArray.some(data => item.annotation.includes(data)));

can somebody help me? thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source