Migration script example to rename object field

4 replies
Last updated: Mar 10, 2023
Does anyone have an example of a migration script to change the
name
field of an object?
AI Update

Yes! Here's how you can rename a field in your documents using a migration script.

The Content migration cheat sheet has exactly what you need. Here's the pattern for renaming a field:

import {defineMigration, at, setIfMissing, unset} from 'sanity/migrate'

export default defineMigration({
  title: 'Rename field from oldName to newName',
  documentTypes: ['yourDocumentType'], // specify which document types to migrate
  
  migrate: {
    document(doc, context) {
      return [
        at('newName', setIfMissing(doc.oldName)),
        at('oldName', unset())
      ]
    }
  }
})

The key operations here are:

  1. setIfMissing() - Sets the new field name with the value from the old field
  2. unset() - Removes the old field name

To create and run this migration:

# Create a new migration script
npx sanity migration create "Rename field from oldName to newName"

# Dry run first (always recommended!)
npx sanity migration run <migration-id>

# Execute for real when you're confident
npx sanity migration run <migration-id> --no-dry-run

If you're renaming a field inside a nested object, you can use dot notation in the path:

at('myObject.newFieldName', setIfMissing(doc.myObject?.oldFieldName)),
at('myObject.oldFieldName', unset())

The migration tool is really nice because it runs in dry-run mode by default, validates against your schema, and batches mutations automatically to avoid rate limits. You can find more details in the schema and content migrations documentation.

Show original thread
4 replies
This should cover what you’re looking for!
Thanks User I was just looking for this.
Just curious, are there any plans to make this process a little more intuitive?
I forgot to reply to this, but I ended up going with the approach of exporting the dataset, doing a find-and-replace and then importing. This way was really simple.What I was trying to do was change the name of an object which is being used across multiple documents and within arrays, and the migration script approach felt way too complicated.
That does seem easier, I’ll try that! I’m in the same situation where I need to change the name of an object and the script method definitely seems overly complicated.

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?