Updating default field value in Sanity.io using a script
Great question! You'll want to use a migration script to update all existing posts with the new isHighlighted field. Sanity provides a CLI migration tool that's perfect for this scenario.
Using the Sanity CLI Migration Tool
First, create a new migration script:
npx sanity@latest migration createThis will generate a migration file where you can write your logic. Here's what your migration should look like:
import {defineMigration, at, setIfMissing} from 'sanity/migrate'
export default defineMigration({
title: 'Set isHighlighted to false for all posts',
documentTypes: ['post'],
migrate: {
document(doc, context) {
return at('isHighlighted', setIfMissing(false))
}
}
})The key here is using setIfMissing, which only sets the value if the field doesn't already exist. This means:
- Existing posts without the field will get
isHighlighted: false - Any posts that already have a value won't be changed
- The migration is idempotent (safe to run multiple times)
Running the Migration
The CLI runs in dry-run mode by default, so you can safely test it first:
npx sanity@latest migration runOnce you've verified the changes look correct, run it for real:
npx sanity@latest migration run --no-dry-runAlternative: Using sanity exec
If you prefer a more direct approach, you can also use sanity exec with a custom script:
// scripts/setIsHighlighted.js
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
const fetchDocuments = () =>
client.fetch(`*[_type == "post" && !defined(isHighlighted)]`)
const buildPatches = docs =>
docs.map(doc => ({
id: doc._id,
patch: {
setIfMissing: {isHighlighted: false}
}
}))
const createTransaction = patches =>
patches.reduce((tx, patch) => tx.patch(patch.id, patch.patch), client.transaction())
const commitTransaction = tx => tx.commit()
const migrateNextBatch = async () => {
const documents = await fetchDocuments()
if (documents.length === 0) {
console.log('No more documents to migrate!')
return
}
console.log(`Migrating batch of ${documents.length} documents...`)
const patches = buildPatches(documents)
const transaction = createTransaction(patches)
await commitTransaction(transaction)
await migrateNextBatch()
}
migrateNextBatch().catch(err => {
console.error(err)
process.exit(1)
})Run it with:
npx sanity exec scripts/setIsHighlighted.js --with-user-tokenThe CLI migration tool is generally recommended as it provides better visual feedback and automatic batching to avoid rate limits. Both approaches will work, but the migration tool is more user-friendly for this type of schema update! 🎉
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.