Reputation: 754
What is the correct way to add an array of references using the Sanity HTTP API?
I'm able to add a single reference:
const mutations = [{
createOrReplace: {
_id: '123',
_type: 'cms.article',
title: 'An article',
author: {
_ref: '12f90f00-8cfb-4161-8bea-26180',
_type: 'reference'
},
}
}]
I expected adding an array of references to existing tags
would work (it returns with Status 200)
const mutations = [{
createOrReplace: {
_id: '123',
_type: 'cms.article',
title: 'An article',
author: {
_ref: '12f90f00-8cfb-4161-8bea-26180',
_type: 'reference'
},
tags: [
{
_ref: 'foo',
_type: 'reference'
},
{
_ref: 'bar',
_type: 'reference'
},
]
}
}]
But Sanity Studio crashes with Error: Unsupported path segment {}
when I attempt to view the document.
Upvotes: 1
Views: 1542
Reputation: 96
It may help to break this down:
First, a reference is an object that contains a _type
and a _ref
. The _type
will always be 'reference'
and the _ref
will always be the _id
of the document you're referencing.
Second, an array can be either an array of strings or of objects. Either way, any item in an array needs a unique _key
.
So, putting all of that together, your mutation would look like this:
field: [
{
_key: '<some-uuid>'
_ref: '<_id-of-document>',
_type: 'reference'
},
]
When it comes to generating keys, you can use an external package (uuid is common) or if you're using the JS client auto generate keys by passing { autoGenerateArrayKeys: true }
to your commit().
Upvotes: 2