mycodeself / mongo-migrate-ts

Run mongodb migrations easy from TypeScript
MIT License
87 stars 28 forks source link

No migrations found #81

Closed silverpedak closed 1 year ago

silverpedak commented 1 year ago

Steps I have taken

  1. npm install mongo-migrate-ts
  2. mkdir migrations
  3. touch index.ts

index.ts


import { mongoMigrateCli } from "mongo-migrate-ts";

const MONGO_URL = "mongodb://localhost:27017";

mongoMigrateCli({
  uri: MONGO_URL,
  database: "db",
  migrationsDir: "migrations",
  migrationsCollection: "migrations_collection",
});

migrations/migration_1.ts

import { MigrationInterface } from "mongo-migrate-ts";
import { Db } from "mongodb";
import { getItem, MY_COLLECTION } from "../common";

export class MyMigration implements MigrationInterface {
  async up(db: Db): Promise<any> {
    const item = getItem();
    const data = await db
      .collection(MY_COLLECTION)
      .find()
      .toArray();
    if (data.length === 0) {
      await db.collection(MY_COLLECTION).insertOne(item);
    }
  }

  async down(db: Db): Promise<any> {
    const item = getItem();
    await db.collection(MY_COLLECTION).deleteOne(resident);
  }
}
  1. tsc index.ts && node index.js up

response: ⚠ No migrations found

Tryed installing globally and using CLI, resilt is the same

FlawaCLV commented 1 year ago

@silverpedak I have the same issue, can you publish the solution please? Thanks!

silverpedak commented 1 year ago

Try changing the migrationsDir in your mongoMigrateCli to "build/migrations". In the root dir of your project, compile the Typescript code with tsc. You should have a /build folder now, that contains the compiled code. Run the code with node build/index.js up.

my src/index.ts

import { mongoMigrateCli } from "mongo-migrate-ts";

mongoMigrateCli({
  uri: your-mongo-URL,
  database: "your-db-name",
  migrationsDir: "build/migrations",
  migrationsCollection: "migrations_collection",
});

my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es6"],
    "allowJs": true,
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

Hope this helps

FlawaCLV commented 1 year ago

Thanks @silverpedak for your reply!

Actually, because I first manually altered the DB, I wanted to run the down migration first... because no migration had previously ran, nothing was stored in the migration_changelog collection, so no migration could be undone. After running a up migration, I was able to run the down migration without any issue.