See Sanity in action 👀 Join us for a live product demo + Q&A →

Converting portable text to plaintext in using a script

5 replies
Last updated: Mar 3, 2023
Hey peeps. Can someone help me to convert my post.body which is a portable text onject(schema type block) to plaintext. I need it for my SCHEMA
Mar 3, 2023, 12:02 AM
You could run a script over your documents that queries for
, sets that in a
field, and then unsets the portable text field. The following should work to copy over to the new field. Note it’s a v2 script so if you’re using v3, you’ll want to adjust the client import. It also doesn’t unset (i.e., remove) the old portable text, as I’m not sure whether you want that or not.

/* eslint-disable no-console */
import sanityClient from 'part:@sanity/base/client'
const client = sanityClient.withConfig({ apiVersion: '2023-03-02' })

const fetchDocuments = () => client.fetch(`*[_type == 'post' && plaintext != pt::text(body)]{_id, _rev, plaintext, 'body': pt::text(body)}`)

const buildPatches = docs => ( => ({
		id: doc._id,
		patch: {
			set: {
				plaintext: doc.body
			ifRevisionID: doc._rev,

const createTransaction = patches =>
  patches.reduce((tx, patch) => tx.patch(, patch.patch), client.transaction())

const commitTransaction = tx => tx.commit()

const editNextBatch = async () => {
  const documents = await fetchDocuments()
  const patches = buildPatches(documents)

  if (patches.length === 0) {
    console.log('No more documents to edit!')
    return null

    `Editing batch:\n %s`, => `${} => ${JSON.stringify(patch.patch)}`).join('\n')
  const transaction = createTransaction(patches)
  await commitTransaction(transaction)
  return editNextBatch()

editNextBatch().catch(err => {
Mar 3, 2023, 12:27 AM
Scripts can be saved anywhere you’d like (I put mine in
) and are run with
sanity exec scripts/scriptName.js --with-user-token
flag is needed when a script needs to do something requiring adequate permissions).
Mar 3, 2023, 12:30 AM
I am in v3, I have this example
Mar 3, 2023, 12:30 AM
I would like a plaintext object for the article body
Mar 3, 2023, 12:31 AM
Cool. The above is how you could do it. 😀
Mar 3, 2023, 12:32 AM – build remarkable experiences at scale

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