How to write Knex migrations — Intermediate
Use exports.up and exports.down to version schema changes in migration files.
Learn: Migrations version schema changes in code reviewable steps. `up` applies; `down` rolls back. Run migrations in CI and production so every environment shares the same table definitions.
Supplementary examples
Create table migration
exports.up = function (knex) {
return knex.schema.createTable("pastes", (table) => {
table.increments("paste_id").primary();
table.integer("user_id").notNullable();
table.text("name").notNullable();
table.timestamps(true, true);
});
};
exports.down = function (knex) {
return knex.schema.dropTable("pastes");
};Course example
exports.up = function (knex) {
return knex.schema.createTable("suppliers", (table) => {
table.increments("supplier_id").primary(); // Sets supplier_id as the primary key
table.string("supplier_name");
table.string("supplier_address_line_1");
table.string("supplier_address_line_2");
table.string("supplier_city");
table.string("supplier_state");
table.string("supplier_zip");
table.string("supplier_phone");
table.string("supplier_email");
table.text("supplier_notes");
table.string("supplier_type_of_goods");
table.timestamps(true, true); // Adds created_at and updated_at columns
});
};
Additional references & examples
- Knex migrations
How to create, run, and roll back schema migrations.
- Thinkful — Node, Express, Postgres starter
Starter repo used across Knex and Express lessons.