Bulk deleting posts with referential integrity protection in Sanity.io
No, you cannot override or force delete documents that have strong references from other documents. This is by design for referential integrity protection in Sanity.
However, you have several options to handle this situation:
1. Use Weak References (Schema Change)
If you want to allow deletion regardless of references, you can modify your schema to use weak references by adding weak: true:
{
name: 'someField',
type: 'reference',
to: [{type: 'work'}],
weak: true // Allows deletion even if referenced
}Important: Just changing this property won't automatically update existing references in your data store.
2. Delete Only Unreferenced Documents
You can filter your query to only delete documents that don't have incoming references:
const posts = await client.fetch(`
*[_type == 'work' && count(*[references(^._id)]) == 0][0...500]
{ title, _id, _rev }
`)3. Identify Which Documents Are Blocking Deletion
To see which documents are preventing deletion, catch the error and query for referencing documents:
posts.forEach((post) => {
queue.add(() =>
client
.delete(post._id)
.catch((err) => {
console.error('Delete failed: ', err.message)
client.fetch('*[references($id)]._id', { id: post._id })
.then((results) => {
console.log('The following documents reference this document:')
results.forEach((id) => console.log(' ', id))
})
})
)
})4. Delete References First
The proper approach is to delete or update the documents that reference your target documents first, then delete the target documents themselves.
Why There's No Force Delete
The strong reference protection is intentional—it prevents orphaned references and maintains data integrity in your content lake. If you truly need to bulk delete documents with references, you'll need to handle the referencing documents first, either by:
- Deleting them
- Updating them to remove the references
- Converting the references to weak references
If you're trying to roll back mutations (as mentioned in the linked discussion), consider using the unset operation to remove specific fields rather than deleting entire documents.
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.