Migrations require your application's environment variables (like DATABASE_URL) to be present in the terminal session.
Create a migration
Generate a new migration file with a descriptive name:
sequelize migration:create --name="meaningful-name"
Files are stored in migrations/scripts with a timestamp prefix (e.g., 20160421135254-meaningful-name.js) to ensure correct execution order.
Writing up/down scripts
Each migration must implement up (to apply) and down (to undo) functions.
Note: When using changeColumn, you must always specify the type, even if the type is not changing.
Example of changing a column from NOT NULL to nullable:
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.changeColumn('tableName', 'columnName', {
type: Sequelize.STRING,
allowNull: true
});
},
down: function (queryInterface, Sequelize) {
return queryInterface.changeColumn('tableName', 'columnName', {
type: Sequelize.STRING,
allowNull: false
});
}
};
Apply and Undo migrations
- Apply all pending migrations:
sequelize db:migrate - Undo the last migration:
sequelize db:migrate:undo
ProTip: You can automate migrations by adding them to your app startup script in package.json:
"scripts": {
"start": "sequelize db:migrate && node src/"
}
sequelize migration:create --name="meaningful-name"
sequelize db:migrate
sequelize db:migrate:undo