| name | migration-helper |
| description | Plan and execute Convex schema migrations safely, including adding fields, creating tables, and data transformations. Use when schema changes affect existing data. |
Convex Migration Helper
Safely migrate Convex schemas and data when making breaking changes.
When to Use
- Adding new required fields to existing tables
- Changing field types or structure
- Splitting or merging tables
- Renaming fields
- Migrating from nested to relational data
Migration Principles
- No Automatic Migrations: Convex doesn't automatically migrate data
- Additive Changes are Safe: Adding optional fields or new tables is safe
- Breaking Changes Need Code: Required fields, type changes need migration code
- Zero-Downtime: Write migrations to keep app running during migration
Safe Changes (No Migration Needed)
Adding Optional Field
users: defineTable({
name: v.string(),
})
users: defineTable({
name: v.string(),
bio: v.optional(v.string()),
})
Adding New Table
posts: defineTable({
userId: v.id("users"),
title: v.string(),
}).index("by_user", ["userId"])
Adding Index
users: defineTable({
name: v.string(),
email: v.string(),
})
.index("by_email", ["email"])
Breaking Changes (Migration Required)
Adding Required Field
Problem: Existing documents won't have the new field.
Solution: Add as optional first, backfill data, then make required.
users: defineTable({
name: v.string(),
email: v.optional(v.string()),
})
import { internalMutation } from "./_generated/server";
import { v } from "convex/values";
export const backfillEmails = internalMutation({
args: {},
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
if (!user.email) {
await ctx.db.patch(user._id, {
email: `user-${user._id}@example.com`,
});
}
}
},
});
users: defineTable({
name: v.string(),
email: v.string(),
})
Changing Field Type
Example: Change tags: v.array(v.string()) to separate table
tags: defineTable({
name: v.string(),
}).index("by_name", ["name"]),
postTags: defineTable({
postId: v.id("posts"),
tagId: v.id("tags"),
})
.index("by_post", ["postId"])
.index("by_tag", ["tagId"]),
posts: defineTable({
title: v.string(),
tags: v.optional(v.array(v.string())),
})
export const migrateTags = internalMutation({
args: { batchSize: v.optional(v.number()) },
handler: async (ctx, args) => {
const batchSize = args.batchSize ?? 100;
const posts = await ctx.db
.query("posts")
.filter(q => q.neq(q.field("tags"), undefined))
.take(batchSize);
for (const post of posts) {
if (!post.tags || post.tags.length === 0) {
await ctx.db.patch(post._id, { tags: undefined });
continue;
}
for (const tagName of post.tags) {
let tag = await ctx.db
.query("tags")
.withIndex("by_name", q => q.eq("name", tagName))
.unique();
if (!tag) {
const tagId = await ctx.db.insert("tags", { name: tagName });
tag = { _id: tagId, name: tagName };
}
const existing = await ctx.db
.query("postTags")
.withIndex("by_post", q => q.eq("postId", post._id))
.filter(q => q.eq(q.field("tagId"), tag._id))
.unique();
if (!existing) {
await ctx.db.insert("postTags", {
postId: post._id,
tagId: tag._id,
});
}
}
await ctx.db.patch(post._id, { tags: undefined });
}
return { migrated: posts.length };
},
});
posts: defineTable({
title: v.string(),
})
Renaming Field
users: defineTable({
name: v.string(),
displayName: v.optional(v.string()),
})
export const renameField = internalMutation({
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
await ctx.db.patch(user._id, {
displayName: user.name,
});
}
},
});
users: defineTable({
displayName: v.string(),
})
Migration Patterns
Batch Processing
For large tables, process in batches:
export const migrateBatch = internalMutation({
args: {
cursor: v.optional(v.string()),
batchSize: v.number(),
},
handler: async (ctx, args) => {
const batchSize = args.batchSize;
let query = ctx.db.query("largeTable");
const items = await query.take(batchSize);
for (const item of items) {
await ctx.db.patch(item._id, {
});
}
return {
processed: items.length,
hasMore: items.length === batchSize,
};
},
});
Scheduled Migration
Use cron jobs for gradual migration:
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";
const crons = cronJobs();
crons.interval(
"migrate-batch",
{ minutes: 5 },
internal.migrations.migrateBatch,
{ batchSize: 100 }
);
export default crons;
Dual-Write Pattern
For zero-downtime migrations:
export const createPost = mutation({
args: { title: v.string(), tags: v.array(v.string()) },
handler: async (ctx, args) => {
const user = await getCurrentUser(ctx);
const postId = await ctx.db.insert("posts", {
userId: user._id,
title: args.title,
tags: args.tags,
});
for (const tagName of args.tags) {
let tag = await ctx.db
.query("tags")
.withIndex("by_name", q => q.eq("name", tagName))
.unique();
if (!tag) {
const tagId = await ctx.db.insert("tags", { name: tagName });
tag = { _id: tagId };
}
await ctx.db.insert("postTags", {
postId,
tagId: tag._id,
});
}
return postId;
},
});
Testing Migrations
Verify Migration Success
export const verifyMigration = query({
args: {},
handler: async (ctx) => {
const total = (await ctx.db.query("users").collect()).length;
const migrated = (await ctx.db
.query("users")
.filter(q => q.neq(q.field("newField"), undefined))
.collect()
).length;
return {
total,
migrated,
remaining: total - migrated,
percentComplete: (migrated / total) * 100,
};
},
});
Migration Checklist
Common Pitfalls
- Don't make field required immediately: Always add as optional first
- Don't migrate in a single transaction: Batch large migrations
- Don't forget to update queries: Update all code using old field
- Don't delete old field too soon: Wait until all data migrated
- Test thoroughly: Verify migration on dev environment first
Example: Complete Migration Flow
export default defineSchema({
users: defineTable({
name: v.string(),
}),
});
export default defineSchema({
users: defineTable({
name: v.string(),
role: v.optional(v.union(
v.literal("user"),
v.literal("admin")
)),
}),
});
export const addDefaultRoles = internalMutation({
handler: async (ctx) => {
const users = await ctx.db.query("users").collect();
for (const user of users) {
if (!user.role) {
await ctx.db.patch(user._id, { role: "user" });
}
}
},
});
export default defineSchema({
users: defineTable({
name: v.string(),
role: v.union(
v.literal("user"),
v.literal("admin")
),
}),
});