mongo-migrate-ts
mongo-migrate-ts copied to clipboard
Order of execution for migrations issue
Hi! 👋
Firstly, thanks for your work on this project! 🙂
Today I used patch-package to patch [email protected]
for the project I'm working on.
I encountered an issue with the order of execution for migrations. Migrations were not being executed in the correct order, which caused inconsistencies in the database state.
Here is the diff that solved my problem:
diff --git a/node_modules/mongo-migrate-ts/dist/lib/commands/up.js b/node_modules/mongo-migrate-ts/dist/lib/commands/up.js
index a702616..7763a0f 100644
--- a/node_modules/mongo-migrate-ts/dist/lib/commands/up.js
+++ b/node_modules/mongo-migrate-ts/dist/lib/commands/up.js
@@ -9,6 +9,7 @@ const config_1 = require("../config");
const database_1 = require("../database");
const errors_1 = require("../errors");
const migrations_1 = require("../migrations");
+const { basename } = require('path');
const up = async (opts) => {
const { uri, database, options, migrationsCollection, migrationsDir, globPattern, globOptions, } = (0, config_1.processConfig)(opts.config);
let connection;
@@ -23,7 +24,12 @@ const up = async (opts) => {
const collection = connection.getMigrationsCollection(migrationsCollection);
const appliedMigrations = await (0, database_1.getAppliedMigrations)(collection);
const migrationObjs = await (0, migrations_1.loadMigrations)(migrationsDir, globPattern, globOptions);
- const migrations = migrationObjs.filter((migration) => appliedMigrations.find((m) => m.className === migration.className) === undefined);
+ const getTimestamp = (filePath) => basename(filePath).split('_')[0];
+ const migrations = migrationObjs.filter((migration) => appliedMigrations.find((m) => m.className === migration.className) === undefined).sort((a, b) => {
+ const aTimestamp = Number(getTimestamp(a.file));
+ const bTimestamp = Number(getTimestamp(a.file));
+ return aTimestamp > bTimestamp ? 1 : -1;
+ });
if (migrations.length === 0) {
spinner.warn('No migrations found').stop();
return;
This patch ensures that the migrations are sorted by their timestamp extracted from the filename before being applied, fixing the order of execution issue.
This issue body was partially generated by patch-package.