//Hook into the createSchemaCustomization API //This hook runs after all our nodes have been created exports.createSchemaCustomization = ({ actions, schema }) => { //The createTypes action allows us to create custom types //and modify existing ones const { createTypes } = actions // Create our schema customizations const typeDefs = [ // Replace "SanityReview" with your _typename of your post type "type SanityReview implements Node { related: [SanityReview] }", schema.buildObjectType({ name: "SanityReview", fields: { related: { type: "[SanityReview]", //The resolve field is called when your page query looks for related posts //Here we can query our data for posts we deem 'related' //Exactly how you do this is up to you //I'm querying purely by category //But you could pull every single post and do a text match if you really wanted //(note that might slow down your build time a bit) //You could even query an external API if you needed resolve: async (source, args, context, info) => { //source is the current (post) object //context provides some methods to interact with the data store //Map a simple array of category IDs from our source object //In my data each category in the array is an object with a _id field //We're just flattening that to an array of those _id values //E.g. categories = ["1234", "4567", "4534"] const categories = source.categories.map((c) => c._id) //If this post has no categories, return an empty array if (!categories.length) return ["uncategorized"] //Query the data store for posts in our target categories const post = await context.nodeModel.runQuery({ query: { filter: { //We're filtering for categories that are sharedby our source node categories: { elemMatch: { _id: { in: categories } } }, //Dont forget to exclude the current post node! _id: { ne: source._id }, }, }, //Change this to match the data type of your post //This will vary depending on how you source content type: "SanityReview", }) //Gatsby gets unhappy if we return "null" here //So check the result and either return an array of post, //or an empty array return post && post.length ? post : [] }, }, }, }), ] createTypes(typeDefs) }