---
title: "Migrate data"
description: "Change documents that already exist in batches while the app keeps running, with Convex's migrations component: define a migration, dry-run it, run and resume it, and let upgrade run the package's own."
canonical_url: "https://nuxt-backend.dev/docs/build/data/jobs/migrations"
---
# Migrate data

> Change documents that already exist in batches while the app keeps running, with Convex's migrations component: define a migration, dry-run it, run and resume it, and let upgrade run the package's own.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: recipe · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Give every existing strip a `status` before you make the field required. A schema change that existing documents do not satisfy yet is made in three steps: deploy the field as optional, migrate every document, then make it required. The official [`@convex-dev/migrations`](https://www.convex.dev/components/migrations) component does the middle step online, a batch per transaction, while the app keeps serving, and resumes where it stopped. Your app imports it directly.

## Fill in a new field

```bash
npm install @convex-dev/migrations
```

<code-tree default-value="backend/migrations.ts">

```ts [backend/convex.config.ts]
import migrations from '@convex-dev/migrations/convex.config'

// …after the package's components
app.use(migrations)
```

```ts [backend/migrations.ts]
import { Migrations } from '@convex-dev/migrations'
import { components } from './_generated/api'
import schema from './schema'

export const migrations = new Migrations(components.migrations, { schema })

// Runs any migration below by name.
export const run = migrations.runner()

export const setDefaultStatus = migrations.define({
  table: 'strips',
  migrateOne: strip => (strip.status === undefined ? { status: 'draft' } : undefined),
})
```

</code-tree>

`migrateOne` runs inside a mutation, one document at a time, a batch per transaction. Return a partial document and the component patches it, or write through `ctx.db` yourself. `schema` types `strip` and lets a migration narrow its pass to an index range with `customRange`.

## Run it

```bash
# Dry run: one batch, then roll back. See what it would do.
npx convex run migrations:run '{ "fn": "migrations:setDefaultStatus", "dryRun": true }'

# Start, or resume where it stopped. A finished migration does nothing.
npx convex run migrations:run '{ "fn": "migrations:setDefaultStatus" }'

# Several, one after another.
npx convex run migrations:run '{ "fn": "migrations:setDefaultStatus", "next": ["migrations:backfillStripCount"] }'
```

Add `--prod` to run on production, after the deploy that defines the migration. From code, `migrations.runOne(ctx, internal.migrations.setDefaultStatus)` starts one from a mutation or an action, `migrations.runSerially(ctx, [...])` runs a series, and `migrations.getStatus(ctx, {})` reads where each stands. A query can return that status to a page.

A migration is also how you backfill an [aggregate](https://nuxt-backend.dev/docs/build/data/read-write/aggregates) over rows that predate its trigger: `migrateOne: (ctx, strip) => stripsPerWorkspace.insertIfDoesNotExist(ctx, strip)`.

## Make it required without blocking the deploy

The last step, `status` made required, has Convex check every existing strip against the new validator, and on a large table that check holds the deploy until it is done. Stage the change instead, with `.staged()` on the table:

```ts [backend/schema.ts]
strips: defineTable({
  title: v.string(),
  status: v.optional(v.string()),
}).staged({
  status: v.string(),
}),
```

The validator in `defineTable` stays the one Convex enforces on writes. It checks the existing documents and every new write against the staged one in the background. `npx convex deploy` and `npx convex deploy --dry-run` report each staged table as validating, validated or failed. Once it reads validated, move the change into `defineTable` and drop `.staged()`: that deploy goes through without scanning the table.

- **What it takes.** For a table defined as an object, only the fields to add or change, and a field set to `undefined` to remove it. A nested object takes its whole validator, and a table defined as a union takes a full validator.
- **Dropping it early.** A deploy that would discard a staged validator, pending or validated, asks first, and staging it again starts the check from zero. In CI, where nothing can answer, pass `--allow-unstaging-schema`.
- **Indexes stage too.** `.index(name, { fields, staged: true })` backfills an index in the background instead of holding the deploy. A staged index answers no query until you remove `staged`.

`.staged()` needs `convex` 1.47 or later; the package's peer range starts at 1.46. See [Staged validators](https://docs.convex.dev/database/schemas#staged-validators) in the Convex docs.

## The package's own migrations

The `backend` component migrates its own tables the same way, on a migrations component nested inside it, so their record stays beside the tables they change and apart from yours. A release that changes data an earlier one wrote ships a migration for it. [`npx nuxt-backend upgrade`](https://nuxt-backend.dev/docs/reference/cli#upgrade) runs the ones a deployment has not finished, on the dev deployment, or on production with `--prod --yes` after its deploy. Each changes a document only while it still needs the change, so running one again changes nothing.

<table>
<thead>
  <tr>
    <th>
      Migration
    </th>
    
    <th>
      Since
    </th>
    
    <th>
      What it does
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        personalWorkspaces
      </code>
    </td>
    
    <td>
      0.2.0
    </td>
    
    <td>
      Gives each signed-in user (one with a live session) without a workspace the personal one their sign-in would have made. Anyone else gets it at their next sign-in, which asks your <code>
        canSignIn
      </code>
      
       first: the migration runs in the component and cannot ask it. A banned user gets it at their first sign-in once the ban ends
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        activeWorkspaces
      </code>
    </td>
    
    <td>
      0.2.0
    </td>
    
    <td>
      Activates the user's first workspace on each live session that has none, so nobody signs in again for it
    </td>
  </tr>
</tbody>
</table>

`upgrade` repairs the scaffold and runs these, and nothing else: there is no codemod from `0.1` ([Upgrade](https://nuxt-backend.dev/docs/ship/releases/upgrade)).

## Related

- [Your data](https://nuxt-backend.dev/docs/build/data/your-data#change-it-later): change a table in steps, with a migration in the middle.
- [Keep counts and sums](https://nuxt-backend.dev/docs/build/data/read-write/aggregates): backfill an aggregate over rows that predate its trigger.
- [`nuxt-backend upgrade`](https://nuxt-backend.dev/docs/reference/cli#upgrade): runs the package's own migrations.
- The [migrations component](https://www.convex.dev/components/migrations): every option, including batch size and `customRange`.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
