
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeGood news - you don't have to do this manually! Sanity's migration toolkit is perfect for this exact scenario. Here's how to handle converting your string arrays to references:
You'll use defineMigration to create a script that:
// schemas/tag.ts
export default {
name: 'tag',
type: 'document',
fields: [
{
name: 'title',
type: 'string'
}
]
}npx sanity@latest migration create convertTagsToReferencesimport {defineMigration, at, set, unset} from 'sanity/migrate'
export default defineMigration({
title: 'Convert string tags to references',
documentTypes: ['yourDocumentType'], // whatever type has the tags
async *migrate(documents, context) {
// First pass: collect all unique tag strings and create tag documents
const uniqueTags = new Set<string>()
for await (const doc of documents()) {
if (doc.tags && Array.isArray(doc.tags)) {
doc.tags.forEach(tag => uniqueTags.add(tag))
}
}
// Create tag documents and build a mapping
const tagMap = new Map<string, string>()
for (const tagString of uniqueTags) {
const tagId = `tag-${tagString.toLowerCase().replace(/\s+/g, '-')}`
tagMap.set(tagString, tagId)
yield {
_type: 'tag',
_id: tagId,
title: tagString
}
}
// Second pass: update documents to use references
for await (const doc of documents()) {
if (doc.tags && Array.isArray(doc.tags)) {
const tagRefs = doc.tags.map(tagString => ({
_type: 'reference',
_ref: tagMap.get(tagString),
_key: Math.random().toString(36).substr(2, 9)
}))
yield {
id: doc._id,
patch: {
set: {
tags: tagRefs
}
}
}
}
}
}
})sanity migration run convertTagsToReferencesThis shows you what will happen without making changes.
sanity migration run convertTagsToReferences --dataset <your-dataset>Don't forget to update your original document schema to use references:
{
name: 'tags',
type: 'array',
of: [{type: 'reference', to: [{type: 'tag'}]}]
}This approach saves you from hours of manual work and ensures consistency across all your documents. The migration toolkit is specifically designed for these kinds of schema refactors!
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