Using sanity migration to add new documents in Sanity.io
Yes, you absolutely can create new documents with Sanity migrations! While the migrate.document property is designed for iterating over existing documents, the migration API supports a more flexible pattern for creating documents from scratch.
There are two main approaches:
1. Using the async generator pattern (recommended for creating documents)
Instead of using the migrate.document property, you can use an async generator function directly on migrate. This gives you full control to create new documents:
import {defineMigration, createOrReplace, createIfNotExists} from 'sanity/migrate'
export default defineMigration({
title: 'Create new documents',
async *migrate(documents, context) {
// Create documents from external data
const externalData = await fetchSomeData()
for (const item of externalData) {
yield createOrReplace({
_id: `imported-${item.id}`,
_type: 'myDocumentType',
title: item.title,
// ... other fields
})
}
// Or create a single document
yield createIfNotExists({
_id: 'my-specific-id',
_type: 'settings',
siteName: 'My Site'
})
}
})The key mutation functions available from sanity/migrate are:
createOrReplace(doc)- Creates or overwrites a documentcreateIfNotExists(doc)- Only creates if the document doesn't existcreate(doc)- Creates a new document (fails if ID already exists)
2. Creating documents while iterating existing ones
You can also create new documents while processing existing ones by yielding additional mutations:
export default defineMigration({
title: 'Process existing and create new',
documentTypes: ['author'],
async *migrate(documents, context) {
for await (const doc of documents) {
// Modify existing document
yield at('processed', set(true))
// Create a related document
yield createIfNotExists({
_id: `author-bio-${doc._id}`,
_type: 'authorBio',
authorRef: {_type: 'reference', _ref: doc._id},
bio: 'To be written'
})
}
}
})This pattern is particularly useful for importing external data, creating seed data, or generating documents based on transformations of existing content. The migration tool handles batching and rate limiting automatically, making it safe to create large numbers of documents.
You can read more about the defineMigration API in the official documentation.
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.