Bulk reassign references before deleting document in Sanity

3 replies
Last updated: Jul 1, 2020
I have `author`’s that are referenced to multiple
document
types.
If I try to delete an
author
I get warnings about all the `document`s they’re connected to.
Is there an automated method to do a find/replace on those documents, to reassign them to another
author
.
I imagine I could write a script to
sanity exec
this, but wanted to check first if there’s already this functionality somewhere. If not, it could probably be a handy plugin…
AI Update

I don't see a built-in "find and replace" feature in Sanity Studio for bulk reassigning references like authors. However, you're absolutely on the right track thinking about a migration script! This is exactly the kind of scenario where Sanity's migration tooling shines.

Using a Migration Script with defineMigration

You can write a migration script using defineMigration that targets all documents referencing a specific author and replaces them with a new author reference:

import { defineMigration, at, set } from 'sanity/migrate'

const oldAuthorId = 'author-to-remove'
const newAuthorId = 'replacement-author'

export default defineMigration({
  title: 'Reassign author references',
  documentTypes: ['post', 'article'], // List all document types with author refs
  
  migrate: {
    document(doc, context) {
      // Check if this document references the old author
      if (doc.author?._ref === oldAuthorId) {
        return [
          at('author._ref', set(newAuthorId))
        ]
      }
      return []
    }
  }
})

Create this migration with:

npx sanity migration create "Reassign author references"

Then run it:

# Dry run first (safe, no changes)
npx sanity migration run reassign-author-references

# Actually execute it
npx sanity migration run reassign-author-references --dataset production

Alternative: Using sanity exec

If you prefer the sanity exec approach you mentioned, here's a script example:

import {getCliClient} from 'sanity/cli'

const client = getCliClient()

const oldAuthorId = 'author-to-remove'
const newAuthorId = 'replacement-author'

const query = `*[references($oldAuthorId)]`

client.fetch(query, {oldAuthorId}).then(docs => {
  const patches = docs.map(doc => 
    client.patch(doc._id)
      .set({'author._ref': newAuthorId})
  )
  
  return client.transaction(patches).commit()
}).then(() => {
  console.log('Done!')
})

Run with: npx sanity exec reassignAuthor.js --with-user-token

Handling Nested References

If your author references are nested deeper in your documents (like inside arrays or objects), you'll need to adjust the path accordingly. For example, if authors are in an array of contributors:

// For nested references
if (doc.contributors?.some(c => c.author?._ref === oldAuthorId)) {
  return doc.contributors.map((contributor, index) => {
    if (contributor.author?._ref === oldAuthorId) {
      return at(`contributors[${index}].author._ref`, set(newAuthorId))
    }
  }).filter(Boolean)
}

Plugin Option

You're right that this could make a handy plugin! While I don't see an official plugin specifically for find/replace on references, there is a Bulk Actions Table plugin that provides bulk operations capabilities in a table view. It might not have find/replace out of the box, but could potentially be extended for this purpose.

The migration script approach is generally the recommended way for this kind of bulk update because it:

  • Provides automatic batching to avoid rate limits
  • Includes dry-run mode by default for safety
  • Validates documents against your schema
  • Gives you full control over the transformation logic
  • Is idempotent - you can run it multiple times safely

The dry-run feature is especially valuable here - you can see exactly what would change before committing to it, which is perfect for something like reassigning authors across multiple documents.

Hope this helps! The migration tooling is quite powerful once you get the hang of it.

Show original thread
3 replies
Hi Simeon, I think you could rework this snippet to get the documents that reference the original author and then patch them to reference the alternative one: https://github.com/sanity-io/sanity-recipes/blob/master/snippets/renameField.js
Hi Simeon, I think you could rework this snippet to get the documents that reference the original author and then patch them to reference the alternative one: https://github.com/sanity-io/sanity-recipes/blob/master/snippets/renameField.js
Figured this would be it. On it, thanks.

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.

Was this answer helpful?