How to populate a field for existing entries via command line in Sanity?
Absolutely! You can backfill that field using a migration script run through the CLI. This is a common task and Sanity provides great tooling for it.
The modern, recommended approach is to use the sanity migration command, which has built-in batching, dry-run capabilities, and validation. Here's how to do it:
Using sanity migration (Recommended)
First, create a new migration:
npx sanity@latest migration create backfill-my-fieldThis creates a migration file where you can write your logic. Here's an example that backfills a field with a default value:
import { defineMigration, at, setIfMissing } from 'sanity/migration'
export default defineMigration({
title: 'Backfill my new field',
async *migrate(documents) {
// Filter to only documents of your type that are missing the field
yield* documents.byType('yourDocumentType')
.filter('!defined(yourNewField)')
.map((doc) =>
at('yourNewField', setIfMissing('your default value'))
)
}
})Then run it with:
npx sanity@latest migration run backfill-my-fieldBy default, this runs in dry-run mode so you can preview changes. When ready, add --no-dry-run to actually apply the changes.
Using sanity exec (Alternative)
You can also use sanity exec --with-user-token for more custom logic. Create a script file (e.g., backfill.js):
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
// Fetch all documents missing the field
const query = '*[_type == "yourDocumentType" && !defined(yourNewField)]'
const documents = await client.fetch(query)
console.log(`Found ${documents.length} documents to update`)
// Batch update them
const transaction = client.transaction()
documents.forEach(doc => {
transaction.patch(doc._id, {
set: { yourNewField: 'your default value' }
})
})
await transaction.commit()
console.log('Done!')Run it with:
sanity exec backfill.js --with-user-tokenThe --with-user-token flag gives your script authentication with your user permissions.
Important Tips
Always backup first: Export your dataset before running any bulk operations:
sanity dataset exportMake it idempotent: Use filters like
!defined(yourNewField)so you can safely re-run the script without creating duplicates or overwriting data.Use transactions: Batch your mutations into transactions (as shown above) to avoid rate limits and improve performance.
Test with a limit: During development, add
.slice(0, 10)to your documents array to test on just a few documents first.
The sanity migration approach is generally preferred because it handles batching automatically, provides better visual feedback, and validates against your schema. But sanity exec gives you more flexibility for complex custom logic.
Show original thread20 replies
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.