3

I'm trying to fetch posts like category->post1, post2, but some category has no post. So I want to skip/filter those categories. How can I do that?

Query example:

query MyQuery {
  allContentfulCategory(limit: 10, filter: {}) {
    edges {
      node {
        slug
        name
        blog_post {
          slug
        }
      }
    }
  }
}

Screenshot

Thanks

Moni
  • 47
  • 9

1 Answers1

2

If your GraphQL nodes are properly set, you just can:

query MyQuery {
  allContentfulCategory(limit: 10, filter: {blog_post: {slug: {ne: null}}}) {
    edges {
      node {
        slug
        name
        blog_post {
          slug
        }
      }
    }
  }
}

The ne (not equal) filter should do the trick.

Alternatively, you can filter directly using JavaScript code, since it's a null value, it can be easily removed from the node array with:

let filtered = data.allContentfulCategory.edges.node.filter(el => el.blog_post != null);
Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • Thank you so much for your answer, please have a look at this screenshot: https://i.imgur.com/eNBKeVL.png (I've tried {blog_post: {ne: null}}, it says blog_post doesn't have `ne`...) – Moni Apr 21 '21 at 05:50
  • 1
    In that case, filter for a null slug, like `allContentfulCategory(limit: 10, filter: {blog_post: {slug: {ne: null}}}) {` – Ferran Buireu Apr 21 '21 at 05:55
  • Still no luck, blog_post has only one property is elemMatch, screenshot: https://i.imgur.com/0F8rnzw.png – Moni Apr 21 '21 at 06:02
  • and `elemMatch: {slug: {ne: null}}` has no effect here – Moni Apr 21 '21 at 06:03
  • 1
    What about directly `allContentfulCategory(limit: 10, filter: {slug: {ne: null}}) {` You have access to the `slug` according to https://i.imgur.com/eNBKeVL.png – Ferran Buireu Apr 21 '21 at 06:05
  • this slug is category slug, it has nothing to do with `blog_post` and it will never be null. Here `category->blog_post` can be null or `category->blog_post->elemMatch->id,slug,etc`, So I need to filter when `category->blog_post` is null – Moni Apr 21 '21 at 08:24
  • 1
    Another workaround is to filter directly in the JS code, once the request and the fetching is done – Ferran Buireu Apr 21 '21 at 08:32
  • yeah, now filtering via js. Thanks so much for your time :) – Moni Apr 21 '21 at 09:20