This article is about how to do mysql migration in node.js project.
Setup mysql databse
We can setup a docker mysql for example.
after docker container started.
Add packages to your project and configure migrate scripts
package.json
When you run npm start, migration-up will check all migration files and upgrade to the latest before application start.
When you run npm run migrate-down, the current database would only downgrade the latest migration in database. If you want to migrate-down 3 migrations, you should run npm run migrate-down 3 times.
Create database.json
Create a database.json file to the root of project. With database.json, db-migrate would know how to connect to database. db-migrate Configuration
database.json
Make sure you have exported MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD and MYSQL_DATABASE to environment.
If the environment is not specified by the -e or –env option (db-migrate up –config config/database.json -e prod), db-migrate will look for an environment named dev or development. You can change this default behavior with the database.json file:
Create migration files
Create a directory migrations to the root of project.
Create a script new-migration.sh
Execute ./new-migration.sh create-table-user
There will be a new migration file {timestamp}-create-table-user.js generated under ./migrations/
Then you should implement the exports.up function and exports.down function such as
You can always do db.runSql() if syntax of db-migrate cannot feed your demand.