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

17 replies
Last updated: Aug 15, 2024
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
You should be able to by using the migration tools!
https://www.sanity.io/docs/schema-and-content-migrations
Thank you πŸ™
Hi sorry to bother you againcan you give me an help please?
This is the current structure
This will be the new structure
On the migration should I do something like this:
object(node, path, context) {
      if (node._type === 'gallery') {
        return at('images', setIfMissing([]))
      }
    },
I try to run it, but receive this_
Error: sanity.cli.ts does not contain a project identifier ("api.projectId"), which is required for the Sanity CLI to communicate with the Sanity API
Sounds like you need a
sanity.cli.ts
file in the root of your project:
import { defineCliConfig } from "sanity/cli";

export default defineCliConfig({
  api: {
    projectId: "<your-project-id>",
    dataset: "production",
  }
});

https://www.sanity.io/docs/cli
Yeah that it's solved, now only need to figure out how to set on the base object
basically the migration puts
gallery: Image[]
inside of the
gallery
object
What I should do?Should the path on the
at
be empty?
object(node, path, context) {
  if (node._type === 'gallery') {
    return [at('gallery', unset()), at('gallery', set(node.images))];
  }
},

I'm unsure tbh. Haven't really done migrations before, but I would probably make a test environment if you havent already!
Then you can go ham on testing out the commands
Thank you, I figure out now, I don't need the
at
, only need the
set(node.images)
Thank you πŸ™πŸ™πŸ™πŸ™πŸ™
No problem! Good luck with the rest of the project πŸ‘
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?