← Back to Node.js Course | Chapter 9: Database Integration | Lesson 6 of 7

Migrations concept

Migrations are versioned scripts that change your database structure step by step and can be undone.

In this page:

  1. Migrations concept

Migrations concept

Each migration has an up step to apply a change and a down step to revert it, and a table records which have run. This keeps every environment's schema in sync and reviewable in git. Tools include Knex, Prisma Migrate and Sequelize CLI.

Note: Never edit a migration that has already run in production; add a new one.

Example: Migrations concept

javascript
const applied = new Set();
const migrations = [
  { id: 1, up: () => "CREATE TABLE users (id INT)", down: () => "DROP TABLE users" },
  { id: 2, up: () => "ALTER TABLE users ADD name TEXT", down: () => "ALTER TABLE users DROP name" },
];
for (const m of migrations) if (!applied.has(m.id)) { console.log("up  ", m.id, m.up()); applied.add(m.id); }
const last = migrations[migrations.length - 1];
console.log("down", last.id, last.down());

// Output:
// up   1 CREATE TABLE users (id INT)
// up   2 ALTER TABLE users ADD name TEXT
// down 2 ALTER TABLE users DROP name

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Editing old migrations
  2. Making manual schema changes
  3. Forgetting the down step
Chapter Summary
  • Migrations version schema changes
  • up applies, down reverts
  • A table tracks applied ones
  • Commit them to git
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.