Migration script example to rename object field
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:
setIfMissing()- Sets the new field name with the value from the old fieldunset()- 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-runIf 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 thread4 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.