Discussion on fixing a transaction mutation error related to incrementing a field that was not present in Sanity.io
I understand the frustration - this error appearing suddenly on code that was working is definitely confusing. The "Cannot increment because it is not present" error occurs when you try to use inc() on a field that doesn't exist yet in the document.
Since you mentioned this was working until a few days ago, let me address both the technical issue and the "why did it break" question.
Why it might have stopped working:
If your code was genuinely working before, the most likely explanations are:
- The documents themselves changed (perhaps new documents are being created without those fields initialized, or a migration removed them)
- Your document creation/initialization logic changed
- The specific documents you're now operating on have a different structure than before
The inc operation itself requires the field to exist - this behavior hasn't changed in the Sanity client.
The solution: Ensure the field exists before incrementing
According to the official Patches documentation, you need to use setIfMissing to create the field if it doesn't exist. The docs specifically show this pattern:
client
.patch(documentId)
.setIfMissing({ 'stats.visitorCount': 0 })
.inc({ 'stats.visitorCount': 1 })
.commit()For your nested path content.main.tickets, you need to ensure the entire structure exists. The safest approach is to set defaults at each level:
client
.patch(documentId)
.setIfMissing({ content: {} })
.setIfMissing({ 'content.main': {} })
.setIfMissing({ 'content.main.tickets': 0 })
.inc({ 'content.main.tickets': 1 })
.commit()This builds up the nested structure step by step, ensuring each parent exists before going deeper.
Alternative approach:
You can also try using nested object syntax for the initial structure:
client
.patch(documentId)
.setIfMissing({ content: { main: { tickets: 0 } } })
.inc({ 'content.main.tickets': 1 })
.commit()Debugging next steps:
To figure out what changed:
- Query the document before the patch to see if
content.mainexists - Review any recent schema changes or content migrations
- Check your document creation logic to ensure the nested structure is initialized
- Look for any recent updates to
@sanity/clientin your dependencies (though the API behavior itself hasn't changed)
The key takeaway: setIfMissing only works if parent objects already exist. For deeply nested paths, you need to ensure each level of the structure is present before you can increment values within it.
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.