Migrating field structure in Sanity without losing data
17 replies
Last updated: Aug 15, 2024
S
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
It's possible to copy the data from one field to another?
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
imagesfield
It's possible to copy the data from one field to another?
Aug 14, 2024, 7:09 AM
J
You should be able to by using the migration tools!
https://www.sanity.io/docs/schema-and-content-migrations
https://www.sanity.io/docs/schema-and-content-migrations
Aug 14, 2024, 7:19 AM
S
Thank you š
Aug 14, 2024, 7:45 AM
S
Hi sorry to bother you againcan you give me an help please?
Aug 15, 2024, 11:00 AM
S
This is the current structure
Aug 15, 2024, 11:00 AM
S
This will be the new structure
Aug 15, 2024, 11:03 AM
S
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
S
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
J
Sounds like you need a
https://www.sanity.io/docs/cli
sanity.cli.tsfile 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
S
Yeah that it's solved, now only need to figure out how to set on the base object
Aug 15, 2024, 11:23 AM
S
basically the migration puts
gallery: Image[]inside of the
galleryobject
Aug 15, 2024, 11:23 AM
S
What I should do?Should the path on the
atbe empty?
object(node, path, context) { if (node._type === 'gallery') { return [at('gallery', unset()), at('gallery', set(node.images))]; } },
Aug 15, 2024, 11:24 AM
J
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
J
Then you can go ham on testing out the commands
Aug 15, 2024, 11:26 AM
S
Thank you, I figure out now, I don't need the
at, only need the
set(node.images)
Aug 15, 2024, 11:27 AM
S
Thank you ššššš
Aug 15, 2024, 11:27 AM
J
No problem! Good luck with the rest of the project š
Aug 15, 2024, 11:27 AM
S
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.