✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Bulk deleting posts with referential integrity protection in Sanity.io

10 replies
Last updated: Feb 28, 2023
trying to bulk delete some posts, but the mutation fails, I guess it's because these documents have references, but can I override that?

export async function deleteContent() {
  const posts = await client.fetch(`
    *[_type == 'work'][0...500]
    { title, _id, _rev, content, workContent }
  `)

  posts.forEach((post) => {
    queue.add(() => 
      client
        .delete(post._id)
        .then(() => {
          console.log('Post deleted')
        })
        .catch((err) => {
          console.error('Delete failed: ', err.message)
        })
    )
  })
}
Feb 28, 2023, 10:41 AM
It’s helpful to see what error message you get, but if it’s referential integrity protection, then you either have to delete the incoming references, or add
_weak: true
to the reference object(s).
Feb 28, 2023, 10:42 AM
Delete failed:  Mutation(s) failed with 1 error(s)
so not very helpful 🙂
Feb 28, 2023, 10:43 AM
I quickly just want to get rid of these posts, unfortunate that there's no
--force
options or similar 🤔
Feb 28, 2023, 10:45 AM
Yeah, I get it. I guess it would be nice to have a convenience method in the client or something.
To quickly just query docs without incoming references, you can at least do something like this:
*[_type == "work" && count(*[references(^._id)]) == 0]
Feb 28, 2023, 10:49 AM
And this is a brittle, because you risk being rate limited, but it will log out the docs that blocks you at least:
.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))
          }
        })
Feb 28, 2023, 10:52 AM
wait, no, you’re adding the promise to the queue. so it will probably be fine
Feb 28, 2023, 10:53 AM
Thanks!
The reason why I'm asking is because I did some mutations on my dataset. Now I want to roll those back, but importing my backed up dataset does not roll back to the previous state because I guess Sanity wants to make sure I don't lose data.
Feb 28, 2023, 10:54 AM
I have populated some fields which I now want unpopulated 🙂
Feb 28, 2023, 10:54 AM
Aha, I see. You can maybe also adapt this script to “undo” the mutation: https://www.sanity.io/schemas/rename-a-field-across-documents-5cd6f5f0
Feb 28, 2023, 10:55 AM
Ah, yeah, unsetting my field was a good solution. Thanks!
Feb 28, 2023, 11:11 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?