How AI is powering better personalization in e-commerce [with Vercel]. Sign up now

Auto-generate reference field from _id's last 6 characters in Sanity

1 replyLast updated: Nov 29, 2025

How would I make sure each Order document created is automatically assigned a
reference
field that is basically the last 6 characters of the generated
_id
field, uppercased?My sense told me that I should replace the
client.create(order)
with something like
client.transactiion().create(...).patch(<id of order just created>, <functionToAddReference>)
but the issue is that I don't know the
_id
of the just created order, or is there a way to pass it to the patch function?Or perhaps I should just handle the ID generation myself, this way I can perform manipulations on it and provide the
reference
directly in the
create
The point is that I want to avoid making two API calls for dealing with this. Is that possible?
AI Update

You'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.

Why this is the best approach:

Important notes:

Your 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.

Show original thread
1 reply

Was this answer helpful?

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.

Related contributions