all posts

Gatsby Filtering nodes by id contained in array of ids

Published to Blog on 20 Feb 2018


Most, if not all, of the examples for Gatsby templates show using a graphQL query that retrieves the post/posts by slugs. I did things a little differently because my post slugs may not be unique across all categories (I could have /blog/hello-world and /cars/hello-world) and choosing to page blog posts with gatsby-pagination on the category and category-tags pages. I decided to pass a list of post ids as the nodes to those templates, rather than the entire list of posts to display, and then query for any posts having an id in that array of ids.

Supported? Not supported?

This all seemed like a good plan until I ran into my first problem. I needed to figure out the syntax for filtering by an id in an array of ids. After a bit of searching I found an issue on the Gatsby repo that asked for exactly what I needed. And Kyle Mathews replied that it was already supported along with an example filtering tags in [tags]. And it is already supported… kind of. It works for array properties. You can filter by tags where the tag is in [tag1, tag2, tag3]. But you cannot filter by id in [id1, id2, id3]. I recently added a request to add support for “in” and “notin” filtering for properties that are not arrays but in the meantime there is a workaround.

The workaround

Though Gatsby does not currently support filtering by id in [array of ids] it will support filtering by ids in [array of ids] where ids is also an array. But my nodes only have a single string id property, you say? Simple fix: in the onCreateNode handler function of your gatsby-node.js file add a field named ids to each node with a value that is an array with a single element, your existing id: like [ ]. Then you can filter your posts by id using something like this:

filter: { fields: { ids: { in: [$ids] } } }

The same sort of thing can be done for any other fields you would like to filter using “is contained in array”. Hopefully this helps someone else out. Give me a shout at @danhounshell on Twitter if it did.

Dan Hounshell
Web geek, nerd, amateur maker. Likes: apis, node, motorcycles, sports, chickens, watches, food, Nashville, Savannah, Cincinnati and family.
Dan Hounshell on Twitter