How to create a new document inside an array in Sanity

26 replies
Last updated: Sep 4, 2020
Hi everyone! What's the correct way to make a mutation for this type of data in my document?
{
  title: 'Contact options',
  name: 'options',
  type: 'array',
  of: [{ title: 'Option', type: 'option' }]
}

AI Update

For your array field, you have a few different approaches depending on what you want to do with the data. Here's how to handle mutations for that array type:

Using the JavaScript Client

If you're working with the Sanity JavaScript client, here's how to mutate your options array:

Adding items to the array

import { v4 as uuidv4 } from 'uuid';

client
  .patch('document-id')
  .setIfMissing({options: []}) // Ensure the array exists
  .insert('after', 'options[-1]', [
    {
      _type: 'option',
      _key: uuidv4(), // Generate unique key
      // ... your option fields
    }
  ])
  .commit()

Setting the entire array

client
  .patch('document-id')
  .set({
    options: [
      {
        _type: 'option',
        _key: uuidv4(),
        // ... your option fields
      }
    ]
  })
  .commit()

Using the HTTP API directly

If you're using the Mutation API directly:

{
  "mutations": [
    {
      "patch": {
        "id": "document-id",
        "insert": {
          "after": "options[-1]",
          "items": [
            {
              "_type": "option",
              "_key": "unique-key-here",
              // ... your option fields
            }
          ]
        }
      }
    }
  ]
}

Important: The _key property

Every object in a Sanity array must have a unique _key property. This is crucial for:

  • Real-time collaborative editing
  • Proper rendering in Studio
  • Identifying specific items for updates

Use a UUID library to generate these keys programmatically. The Studio generates them automatically, but when using the API directly, you need to provide them yourself.

Other useful array operations

  • Append: Use "after": "options[-1]"
  • Prepend: Use "before": "options[0]"
  • Replace: Use "replace": "options[2:]" to replace from index 2 onwards

Check out the patches documentation for more advanced operations!

This works for editing existing ones under an ID, but how do I create a new document under the same ID?

patch: {

'id': id,

"set": {

'options': [{

'_type': 'option',

'_key': key,

'title': title,

'duration': duration,

'price': price

}]

}

}
Thank you. Due to the project setup I'm not using the client at the moment, although it does make it a lot easier I think
Is there a way to achieve this without?
Yes, with the exception that I'd like to create a new document and it seems patches are for modifying?
I have a document and inside this reference to another one:
{
  title: 'Contact options',
  name: 'options',
  type: 'array',
  of: [{ title: 'Option', type: 'option' }]
}

I want to create a new item (type option) inside this document (profile). I am able to edit existing option items with the below patch query, where ID is the name of parent document (profile):
patch: {

'id': id,

"set": {

'options': [{

'_type': 'option',

'_key': key,

'title': title,

'duration': duration,

'price': price

}]

}

}
Exactly, but the same query doesn't work with "create" instead of "patch"
Can't figure out how to write the correct query?
"mutation failed on document "...": Document does not have a type"
create: {

'id': id,

"set": {

'options': [{

'_type': 'option',

'_key': key,

'title': title,

'duration': duration,

'price': price

}]

}
}
also tried without "set"
You need to provide a document type

_type: 'your-document-type'
yes - I'm sending '_type': 'option'
same as patch query
On the root document
create: {

"_id": id,
 "_type": "your-type",
  "options": [...]

}
(on mobile so excuse my brevity)
Ok, got it! That doesn't result in error but also doesn't create the option item 🤔
strange - still works with "patch" but just overrides the item every time. but doesn't do anything with "create" + document type
the goal is to actually modify an existing document by creating a new one inside
wondering if it has to be patch + create somehow?
patch: {

'id': id,

"insert": {

"before": "options[-1]",

'items': [{

'_type': 'option',

'_key': key,

'title': title,

'duration': duration,

'price': price

}]

}

}
this is what worked

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.

Was this answer helpful?