Skip to content

Commit

Permalink
fix: sort migrations by timestamp from className (#115)
Browse files Browse the repository at this point in the history
  • Loading branch information
mycodeself authored Aug 14, 2024
1 parent dab6f48 commit 63dc812
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
14 changes: 14 additions & 0 deletions examples/migrations/1713446102472_InsertRandomData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Db } from 'mongodb';
import { MigrationInterface } from '../../lib';

export class InsertRandomData1713446102472 implements MigrationInterface {
public async up(db: Db): Promise<void | never> {
const col = db.collection('mycol');
await col.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
}

public async down(db: Db): Promise<void | never> {
const col = db.collection('mycol');
await col.deleteMany({ a: { $in: [1, 2, 3] } });
}
}
11 changes: 10 additions & 1 deletion lib/commands/up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,16 @@ export const up = async (opts: CommandUpOptions): Promise<void> => {
(m: MigrationModel) => m.className === migration.className
) === undefined
)
.sort((a, b) => a.className.localeCompare(b.className));
.sort((a, b): number => {
// sort migrations by timestamp before applying
const aTimestamp = Number(
a.className.substring(a.className.length - 13)
);
const bTimestamp = Number(
b.className.substring(b.className.length - 13)
);
return aTimestamp > bTimestamp ? 1 : -1;
});

if (migrations.length === 0) {
spinner.warn('No migrations found').stop();
Expand Down

0 comments on commit 63dc812

Please sign in to comment.