Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Migrating field structure in Sanity without losing data

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?
Aug 14, 2024, 7:09 AM
You should be able to by using the migration tools!
https://www.sanity.io/docs/schema-and-content-migrations
Aug 14, 2024, 7:19 AM
Thank you šŸ™
Aug 14, 2024, 7:45 AM
Hi sorry to bother you againcan you give me an help please?
Aug 15, 2024, 11:00 AM
This is the current structure
Aug 15, 2024, 11:00 AM
This will be the new structure
Aug 15, 2024, 11:03 AM
On the migration should I do something like this:
object(node, path, context) {
      if (node._type === 'gallery') {
        return at('images', setIfMissing([]))
      }
    },
Aug 15, 2024, 11:05 AM
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
Aug 15, 2024, 11:08 AM
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
Aug 15, 2024, 11:17 AM
Yeah that it's solved, now only need to figure out how to set on the base object
Aug 15, 2024, 11:23 AM
basically the migration puts
gallery: Image[]
inside of the
gallery
object
Aug 15, 2024, 11:23 AM
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))];
  }
},

Aug 15, 2024, 11:24 AM
I'm unsure tbh. Haven't really done migrations before, but I would probably make a test environment if you havent already!
Aug 15, 2024, 11:25 AM
Then you can go ham on testing out the commands
Aug 15, 2024, 11:26 AM
Thank you, I figure out now, I don't need the
at
, only need the
set(node.images)
Aug 15, 2024, 11:27 AM
Thank you šŸ™šŸ™šŸ™šŸ™šŸ™
Aug 15, 2024, 11:27 AM
No problem! Good luck with the rest of the project šŸ‘
Aug 15, 2024, 11:27 AM
Thanks
Aug 15, 2024, 11:27 AM

Sanityā€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?