Example of updating a deeply nested document with @sanity/client ?
Great question! Here are some practical examples for patching deeply nested documents with @sanity/client:
Basic Nested Object Update
For objects nested 2-3 levels deep, you can use dot notation in your path:
client
.patch('document-id')
.set({
'level1.level2.level3.fieldName': 'new value'
})
.commit()Updating Objects in Arrays
When you need to update a specific object within an array, use the JSONMatch path syntax with _key filtering:
client
.patch('document-id')
.set({
'items[_key=="abc123"].title': 'Updated Title',
'items[_key=="abc123"].nested.deepField': 'Deep value'
})
.commit()Deeply Nested Array Updates
For arrays nested within arrays, you can chain conditions:
client
.patch('document-id')
.set({
'sections[_key=="section1"].blocks[_key=="block2"].content': 'New content',
'sections[_key=="section1"].blocks[_key=="block2"].metadata.author': 'John'
})
.commit()Inserting into Nested Arrays
To insert items into a nested array, use the insert() method:
client
.patch('document-id')
.insert('after', 'sections[_key=="section1"].items[-1]', [
{
_key: 'newItem123',
_type: 'item',
title: 'New nested item'
}
])
.commit()Multiple Operations in One Patch
You can chain multiple operations for complex updates:
client
.patch('document-id')
.set({
'level1.level2.field1': 'value1'
})
.setIfMissing({
'level1.level2.field2': 'default value'
})
.unset(['level1.level2.oldField'])
.commit()Important Tips
- Always use
_keywhen targeting specific array items - this is more reliable than using array indices - Path syntax supports conditions like
[_key=="value"]or even[_type=="cta"]to filter array elements - Array positions: Use
[-1]for the last element,[0]for first - The patches documentation has more details on all available operations
The key to deeply nested updates is understanding that you can combine dot notation for objects with bracket notation and conditions for arrays, creating paths like parent.children[_key=="child1"].grandchildren[_key=="gc1"].field.
Show original thread2 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.