Search code examples
node.jsgatsby

Remove nodes from Gatsby


I'm using a plugin that automatically creates nodes for me from an API request. It's working well, but it returns more data than I need, including nodes that aren't relevant for my application. How can I remove nodes while I'm in onCreateNode in gatsby-node?

For example. I only want to have nodes with titles. If it has a title, I want to keep it, and add a field. If it doesn't, I would like to remove it. This is correctly recognizing the node types:

if(node.internal.type === `community_education__classes` && node.title && node.title._t) {
  const correctedClassObject = classCorrector(node.content._t);
  createNodeField({
    node,
    name: `className`,
    value: node.title._t,
  });
}

So I can find the nodes I want to remove like this

if(node.internal.type === `community_education__classes` && (!node.title || !node.title._t)) {
  // need code to delete node that matched these conditions
}

I'm hoping there is a Gatsby API for this that I just can't find?


Solution

  • You can use Gatsby's deleteNode, which is part of actions fka boundActionCreators.

    exports.onCreateNode = ({ node, boundActionCreators }) => {
      const { deleteNode } = boundActionCreators;
    
      // Check the node, delete if true.
      if (condition) {
        deleteNode(node);
      }
    }