Search code examples
javascriptcontentful

Contentful search for field which value also has a field


Let's say for example I have multiple movies listed on my contentful backend and I only want a query to return horror movies so I filter by category.

0:fields{
    name: "Some horror movie"
    category: {sys: {…}, fields: {…}} // fields contains in this example: {name: "horror"}
}

Note that category is a content type itself and has a fields attribute with only a name attribute in there. So I would think I could filter this by doing the following:

client.getEntries({
      'content_type': 'movie',
      'fields.category.fields.name[match]': 'horror'
    })

This returns a 400 error though and I really have no idea why or how to fix this.


Solution

  • The query is correct, but you also need to include a filtering on the referenced content type when you're filtering on a field value. You can read more about that here: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references

    If you add this to your query it should work.

    client.getEntries({
      'content_type': 'movie',
      'fields.category.fields.name[match]': 'horror',
      'fields.category.sys.contentType.sys.id': 'horror-content-type-id'
    })
    

    You can find a complete snippet example here: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references/search-on-references/console/js

    Remember to replace 'horror-content-type-id' with the actual id of the horror content type.