The migration
module for Hexabot provides a simple and effective way to manage database migrations. It allows you to create, execute, and roll back migrations, ensuring the database schema stays in sync with the version DB updates.
Whenever a new version is released which requires some DB updates, the onApplicationBootstrap()
will apply migrations automatically but only if it's a dev environement and config.mongo.autoMigrate
is enabled.
- Generate timestamped migration files automatically in kebab-case.
- Track migration execution status in a MongoDB collection (
migrations
). - Run individual or all migrations with ease.
- Built-in support for rollback logic.
To create a new migration:
npm run cli migration create <version>
Replace <version>
with the next version for your migration, such as v2.1.1
.
Example:
npm run cli migration create v2.1.1
This will generate a new file under src/migration/migrations/
with a timestamped filename in kebab-case.
To execute a specific migration, use:
npm run cli migration migrate up <version>
Example:
npm run cli migration migrate up v2.1.1
To roll back a specific migration, use:
npm run cli migration migrate down <version>
Example:
npm run cli migration migrate down v2.1.1
To execute all pending migrations:
npm run cli migration migrate up
To roll back all migrations:
npm run cli migration migrate down
The migration status is stored in a MongoDB collection called migrations
. This collection helps ensure that each migration is executed or rolled back only once, avoiding duplicate operations.
Below is an example migration file:
import mongoose from 'mongoose';
import attachmentSchema, {
Attachment,
} from '@/attachment/schemas/attachment.schema';
module.exports = {
async up() {
const AttachmentModel = mongoose.model<Attachment>(
Attachment.name,
attachmentSchema,
);
await AttachmentModel.updateMany({
type: 'csv'
}, {
$set: { type: 'text/csv' }
});
},
async down() {
// Rollback logic
const AttachmentModel = mongoose.model<Attachment>(
Attachment.name,
attachmentSchema,
);
await AttachmentModel.updateMany({
type: 'text/csv'
}, {
$set: { type: 'csv' }
});
},
};
up
Method: Defines the operations to apply the migration (e.g., modifying schemas or inserting data).down
Method: Defines the rollback logic to revert the migration.
- Use semantic versioning (e.g.,
v2.1.1
) for your migration names to keep track of changes systematically. - Always test migrations in a development or staging environment before running them in production.
- Keep the
up
anddown
methods idempotent to avoid side effects from repeated execution.