Best way to batch remove deprecated field from Sanity dataset

22 replies
Last updated: Apr 16, 2024
Hi,I'm looking for a efficient way to remove a deprecated field from a Dataset. I have tried executing this
script and tried with a migration script with an unset(). I not having any success atm. What is the best practice when you want to batch remove a field from a dataset.
AI Update

Looking at your situation, the recommended approach for batch removing a deprecated field from your dataset is to use Sanity's migration tooling with the unset() function. Let me walk you through the best practice approach.

Using defineMigration with unset()

First, create a migration script:

npx sanity@latest migration create "Remove deprecated field"

Then in the generated migrations/your-migration-name/index.ts file, use this pattern:

import {defineMigration, at, unset} from 'sanity/migrate'

export default defineMigration({
  title: 'Remove deprecated field',
  documentTypes: ['yourDocumentType'], // specify the document type(s)
  
  migrate: {
    document(doc, context) {
      // Remove the deprecated field
      return at('deprecatedFieldName', unset())
    }
  }
})

Running the Migration

The key to success is following this process:

  1. Always dry-run first (this is the default behavior):
sanity migration run your-migration-name

This shows you what would happen without making actual changes.

  1. Execute on your dataset once you've verified the dry-run looks correct:
sanity migration run your-migration-name --dataset <your-dataset-name>

Why This Approach Works

The defineMigration API handles several important things automatically:

  • Automatic batching to avoid API rate limits
  • Document validation against your schema
  • Visual feedback during execution
  • Safe defaults with dry-run mode

Removing Multiple Fields

If you need to remove multiple deprecated fields at once:

migrate: {
  document(doc, context) {
    return [
      at('deprecatedField1', unset()),
      at('deprecatedField2', unset()),
      at('nested.deprecatedField', unset())
    ]
  }
}

Troubleshooting Tips

If you're still not seeing success:

  1. Check document types: Make sure the documentTypes array matches exactly with your schema type names
  2. Verify field paths: The field name in at() must match the exact field name in your documents
  3. Review dry-run output: Look for any errors or warnings in the terminal output
  4. Check for nested fields: If your field is nested, use dot notation like 'parent.child.fieldName'

The migration tooling is specifically designed for this batch patch use case and handles all the complexity of batching mutations automatically, making it more reliable than manual patching scripts. If you're still experiencing issues after following this pattern, double-check that your field names and document types exactly match what's in your dataset.

Show original thread
22 replies
That script may be giving you problems because it’s still using V2 syntax. That said, it’s overall still the best method for deleting data once corrected.
You can also just
deprecate the field in the UI if you don’t need to delete it.
Is the v3 syntax uses cliClient or createClient constructor? I was able to make it run but, even if I am logged as admin, I get permission errors.
This is how you get the client for a script:
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
To execute the command you’ll need to use the flag
--with-user-token
.
I'm getting the following error with
sanity exec scripts/batchRemoveField.js --with-user-token

  details: {
    description: 'Mutation failed: Insufficient permissions; permission "manage" required',
    items: [ [Object] ],
    type: 'mutationError'
  }
thank you for your time ❤️
Are you logged in via the CLI?
yes!
if you run
sanity debug --secrets
what role does it say you have under User?
User type or user role?
Role
  User role: 'administrator'
but user type is at normal
Is it possible you’re logged into a different account that doesn’t have access to this project? This can happen if you use a different provider to log in than the one you used when you created the project.
hmm, I only have 1 account setup. I don't use email/password to login. No specific provider
It could have happened accidentally if you used something like Google instead of Github to log in, for example.
the project was created when we were still using Google provider. We have migrated to Microsoft this year and we switched to email/password on Sanity
I have no problem to read but it won't allow me to manage/write. I will ask a colleague in the morning to run the script on his account. I will update this tread then. Thanks again for your time
Good morning rd,We have tried a few things this morning but even my manager receives the same
403 forbidden
error. I have tried to also add option in the
getCliClient
constructor like a new token created with
EDITOR
permissions and the results are the same. Is there something I did not think about to try ? Thank you.
What version of the CLI are you on?
Hi again! I was able to make it work! I did update the CLI and also modified my initial GROQ query. It seem I was also fetching items that we are unable to modify. For my current use case, the script works now. Thank you soo much for your time helping me debug and rubber duck me out of there.
Yay! Glad you got it figured out!
I suggest maybe updating the initial script. It is the first to pop up in google when you re searching for remove field in sanity. It could help more people.

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.

Was this answer helpful?