Can I migrate data from object field to array without losing content?

17 replies
Last updated: Nov 29, 2025
Good morning everyoneIt's possible to change a field structure without loose the data?

For example, I have an object, like:`{ images: Image Array, structure: slider | carousel }`

But now, I want to change the field from an object to an array of images, but I don't want to loose the images selected on the
images
field
It's possible to copy the data from one field to another?
AI Update

Yes, absolutely! You can migrate data from one field structure to another without losing your content. Sanity provides migration tooling specifically for this kind of schema restructuring.

For your specific case (moving from an object with an images array to just an array of images), you can use the defineMigration API to copy the data from the nested field to a new field structure.

Here's how you'd approach this:

1. Create a migration script:

npx sanity@latest migration create "migrate-images-field"

2. Write the migration logic:

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

export default defineMigration({
  title: 'Migrate images from object to array',
  documentTypes: ["yourDocumentType"], // replace with your actual document type
  
  migrate: {
    document(doc, context) {
      // Only migrate if the old structure exists
      if (!doc.images?.images) {
        return []
      }
      
      return [
        // Copy the images array to the new structure
        at('newImages', setIfMissing(doc.images.images)),
        // Optionally remove the old field after confirming data is copied
        // at('images', unset())
      ]
    }
  }
})

3. Test with a dry run first:

sanity migration run migrate-images-field

This runs without making changes so you can verify everything looks correct.

4. Execute the migration:

sanity migration run migrate-images-field --dataset <your-dataset>

Important tips:

  • The migration tool is idempotent, meaning you can run it multiple times safely
  • Always test with dry runs first before running on production data
  • Consider keeping both fields temporarily, then remove the old one in a second migration after verifying everything works
  • The migration tool automatically batches mutations to avoid rate limits

You can also update your schema at the same time, or before/after the migration depending on your workflow. The Content Migration documentation recommends an incremental approach - start simple, verify, then add complexity.

Show original thread
17 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.

Was this answer helpful?