
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeYou're on the right track! The best approach here is to generate the _id yourself before creating the document. This allows you to derive the reference field from the ID and include it in a single create() call—no need for a second API call or transaction.
Here's how to do it:
import {v4 as uuidv4} from 'uuid'
const customId = uuidv4() // Generate a UUID like Sanity does
const reference = customId.slice(-6).toUpperCase() // Last 6 chars, uppercased
const order = {
_id: customId,
_type: 'order',
reference: reference,
// ... other fields
}
await client.create(order)This is actually a recommended pattern for content migrations and works perfectly for your use case. Sanity allows you to specify custom _id values when creating documents—they don't have to be auto-generated.
create() operation., _, - up to 128 characters)drafts. prefix for the custom ID—that's reserved for draft documents_id you set is permanent and never changesYour initial instinct about using transactions was creative, but the issue you identified is real: you can't reference the _id of a document being created within the same transaction before it's actually created. By generating the ID upfront, you sidestep this entirely.
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store