Unlock seamless workflows and faster delivery with our latest releases- get the details

Discussion on how to change nested block content in Sanity documents during data migration.

5 replies
Last updated: Apr 26, 2020
Question about migrating data - this example is good (https://www.sanity.io/docs/migrating-data ). It unsets a document's
name
and sets a
fullname
. But let's say for something more complicated
My document has a
body
of block content and for example I want to look at all the blocks inside each document body and find the ones that are
_type == 'ctaButton'
and change them to a new type
_type = 'newCtaButton'
when I change it to the new type I also want to set some new values that didn't exist on the old type.
I see when I get the docs, I can filter down to all the
blocks
inside the
body
that I want to change, but then how do I create patches that will change the
type
of each of these blocks? It seems like maybe patches can only be performed on top-level documents and not child blocks - what's the best way to go about this?

doc.body.filter(block => block._type === 'ctaButton').map(block => ({
  id: block._key,
  patch: {
    set: {}
  }
}))
Apr 26, 2020, 4:31 AM
I believe you can use this script: https://github.com/sanity-io/sanity-recipes/blob/master/snippets/renameField.js
Edit the query:

client.fetch(`*['ctaButton' in body[]._type][0...100] {_id, _rev, name}`)
and edit the patch

{
    id: doc._id,
    patch: {
      set: {
        'body[_type=="ctaButton"]._type': "newCtaButton"
      },
      // this will cause the migration to fail if any of the documents has been
      // modified since it was fetched.
      ifRevisionID: doc._rev
    }
  }

Apr 26, 2020, 5:29 PM
For future reference, this library might be interesting https://www.npmjs.com/package/sanity-diff-patch
Apr 26, 2020, 5:30 PM
I believe you can use this script: https://github.com/sanity-io/sanity-recipes/blob/master/snippets/renameField.js
Edit the query:

client.fetch(`*['ctaButton' in body[]._type][0...100] {_id, _rev, name}`)
and edit the patch

{
    id: doc._id,
    patch: {
      set: {
        'body[_type=="ctaButton"]._type': "newCtaButton"
      },
      // this will cause the migration to fail if any of the documents has been
      // modified since it was fetched.
      ifRevisionID: doc._rev
    }
  }

Apr 26, 2020, 5:29 PM
For future reference, this library might be interesting https://www.npmjs.com/package/sanity-diff-patch
Apr 26, 2020, 5:30 PM
Interesting! Will try that
Apr 26, 2020, 5:45 PM

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?