How to create a new document and set a reference in an array using the JavaScript API.
The issue with your code is in the structure of the reference objects. When creating an array of references in Sanity, each reference object should use _ref (not _id) to point to the referenced document. Here's the correct format:
finalistCategory: [
{
_type: "reference",
_ref: "6c3c48e1-91b1-44b0-bcdc-640037cfabcd", // Use _ref, not _id
_key: "a18b3d20-fd0c-4aeb-8b72-924bcd90d0e1"
},
]Your first example was close but used _id instead of _ref. Your second example had the reference nested inside an awardCategory object, which isn't the correct structure for a reference field.
The correct structure for a reference in Sanity is:
_type: Must be"reference"_ref: The document ID you're referencing (not_id)_key: Required for array items (which you're correctly generating)
So your complete createOrReplace call should look like:
client.createOrReplace({
_id: 'your-document-id',
_type: 'yourDocumentType',
finalistCategory: [
{
_type: "reference",
_ref: "6c3c48e1-91b1-44b0-bcdc-640037cfabcd",
_key: uuidv4().toString(),
},
],
// ... other fields
})Important note: As mentioned in the Sanity documentation on strong references, the referenced document (the one with ID 6c3c48e1-91b1-44b0-bcdc-640037cfabcd) must already exist in your dataset before you create this reference, or it must be created in the same mutation transaction. If it doesn't exist, the operation will fail silently or throw a validation error.
You're right that createOrReplace is the correct method here - patch is only for updating existing documents. createOrReplace works perfectly for creating new documents with references.
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.