Update Feb 18, 2018

After some additional searching, I found the relevant documentation to filter entries by linked content types. Here is the updated query:

asyncData({ params }) {
  return client.getEntries({
    'content_type': 'post',
    'fields.category.sys.contentType.sys.id': 'postCategory',
    'fields.category.fields.slug[match]': params.slug,
  })
    .then(entries => {
    return {
      category: params.slug,
      posts: entries.items,
    };
  })
    .catch(console.error);
},

Original Post

I'm using Nuxt.js and Contentful to power this site. Contentful provides a JavaScript SDK to access the content. The dynamic route I'm using to display my blog posts is /blog/:slug. To get the relevant entry from Contentful, I'm using the following code:

asyncData({ params }) {
  return client.getEntries({
    'content_type': 'post',
    // Return entries with a slug field that matches the slug param
    'fields.slug': params.slug,
  })
    .then(entries => {
      return {
        post: entries.items[0],
      };
    })
    .catch(console.error);
},

Then I needed to get entries that belonged to a certain category at the route /blog/category/:slug, and thought I'd be able to get entries by searching the fields of the linked category content type:

asyncData({ params }) {
  return client.getEntries({
    'content_type': 'post',
     // Trying to search by linked content type fields
    'fields.category.fields.slug': params.slug,
  })
    .then(entries => {
      return {
        posts: entries.items,
      };
    })
    .catch(console.error);
},

Unfortunately, we cannot access the fields of a linked content type in Contentful yet. However, we can access the id of linked content types. It's not as clean as the above, but this is how we can achieve the desired result:

asyncData({ params }) {
  // Get the category by slug
  return client.getEntries({
    'content_type': 'postCategory',
    'fields.slug': params.slug,
  })
    // Pass the category into the second getEntries call
    .then(categories => {
      return client.getEntries({
        'content_type': 'post',
        // Match entries by id of passed category
        'fields.category.sys.id': categories.items[0].sys.id,
      });
    })
    .then(entries => {
      return {
        posts: entries.items,
      };
    })
    .catch(console.error);
},
Back to Blog