How to delete documents from removed schemas or find dangling data in Sanity?
Ah, the classic "deleted the schema before the documents" scenario! Don't worry, this is a common issue and there's a good solution using the Sanity CLI.
Since you removed the schema, those documents are now invisible in Studio, but they still exist in your dataset. Here's how to handle this:
The Solution: Use CLI to Delete Documents
You can delete documents without a schema using the sanity documents delete command. The key is querying for documents by their _type and then deleting them.
Basic Command Structure
sanity documents query "*[_type == 'yourDocumentType'][0...20]._id" --apiVersion 2021-03-25
| groq "*" -o ndjson
| xargs sanity documents deleteImportant notes:
- Replace
'yourDocumentType'with the actual type of the documents you want to delete - The
[0...20]limits the query to 20 documents at a time to avoid timeouts - You'll need to run this multiple times if you have more than 20 documents
Finding All Dangling Documents
To see all documents that might be dangling (without any references), you can query for documents with a specific type, or if you're not sure of the type, you can:
- Export your dataset to see what's there:
sanity dataset export- Query for all document types:
sanity documents query "*[]._type" --apiVersion 2021-03-25This will show you all the document types in your dataset, helping you identify the orphaned ones.
For Faster Bulk Deletion
If you have many documents to delete (50+), the command above can timeout. For better performance, you can use a tool like Console.Join to batch the deletions into a single API call:
sanity documents query "*[_type == 'yourDocumentType']._id" --apiVersion 2021-03-25
| groq "*" -o ndjson
| join
| xargs sanity documents deleteAlternative: Use a Migration Script
For more complex cleanup operations, you might want to use Sanity's migration tooling. Create a migration script with:
npx sanity migration create deleteOrphanedThis gives you more control and better error handling, especially useful if you need to delete documents based on more complex criteria than just type.
The CLI approach is definitely the way to go here - reverting commits won't help since the documents still exist in your dataset regardless of your local schema definitions.
Show original thread5 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.