Converting portable text to plaintext in Sanity.io using a script
5 replies
Last updated: Mar 3, 2023
N
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
pt::text(body), sets that in a
textfield, 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 => ( docs.map(doc => ({ id: doc._id, patch: { set: { plaintext: doc.body }, ifRevisionID: doc._rev, } })) ) const createTransaction = patches => patches.reduce((tx, patch) => tx.patch(patch.id, 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 } console.log( `Editing batch:\n %s`, patches.map(patch => `${patch.id} => ${JSON.stringify(patch.patch)}`).join('\n') ) const transaction = createTransaction(patches) await commitTransaction(transaction) return editNextBatch() } editNextBatch().catch(err => { console.error(err) process.exit(1) })
Mar 3, 2023, 12:27 AM
Scripts can be saved anywhere you’d like (I put mine in (the
scripts/) and are run with
sanity exec scripts/scriptName.js --with-user-token
--with-user-tokenflag is needed when a script needs to do something requiring adequate permissions).
Mar 3, 2023, 12:30 AM
N
I am in v3, I have this example https://jsonld.com/blog-post/
Mar 3, 2023, 12:30 AM
N
I would like a plaintext object for the article body
Mar 3, 2023, 12:31 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.