Git Product home page Git Product logo

ts-migrate-mongoose's Introduction

ts-migrate-mongoose

A node/typescript based migration framework for mongoose

npm npm GitHub
Coverage Quality Gate Status
Reliability Rating Maintainability Rating Security Rating

npm

Motivation

ts-migrate-mongoose is a migration framework for projects which are already using mongoose

Features

  • Stores migration state in MongoDB
  • Flexibility in configuration migrate.json or migrate.ts or .env and/or .env.local
  • Use mongoose models when running migrations
  • Use async/await in migrations
  • Run migrations from the CLI
  • Run migrations programmatically
  • Prune old migrations, and sync new migrations
  • Create custom templates for migrations
  • Supports ESM (not yet) and CommonJS

Example

How to use it with:

Installation

  • Locally inside your project
yarn add ts-migrate-mongoose
npm install ts-migrate-mongoose
pnpm add ts-migrate-mongoose
  • Install it globally
yarn global add ts-migrate-mongoose
npm install -g ts-migrate-mongoose
pnpm add -g ts-migrate-mongoose

Migrations and alias imports

If you are using alias imports in your project, you can use tsconfig.json paths to resolve them for you project.
But ts-migrate-mongoose uses swc to compile the migrations internally, so you also need to add .swcrc file to project root
Starting from "@swc/core": "1.3.74", you need to use target or env not both, in example bellow we use "target": "es2021"

{
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "dynamicImport": true
    },
    "target": "es2021",
    "keepClassNames": true,
    "loose": true,
    // Important part bellow, copy it from your tsconfig.json
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "module": {
    "type": "commonjs"
  },
  "sourceMaps": true
}

Now your migrations will be compiled with swc and you can use alias imports in your migrations.

Configuration

If you don't want to provide -d or --uri flag in CLI or Programmatic mode, you can configure it.
Create a migrate.json or migrate.ts or .env file in the root of your project:

  • migrate.json
{
  "uri": "mongodb://localhost/my-db",
  "collection": "migrations",
  "migrationsPath": "./migrations",
  "templatePath": "./migrations/template.ts",
  "autosync": false
}
  • migrate.ts
export default {
  uri: "mongodb://localhost/my-db",
  collection: "migrations",
  migrationsPath: "./migrations",
  templatePath: "./migrations/template.ts",
  autosync: false,
};
  • .env
# You can set this variable or in your CI/CD pipeline
# Or use --mode flag in CLI mode to switch between .env files
MIGRATE_MODE=development

If mode is set, it will look for .env.[mode] file in the root of your project
For example, if MIGRATE_MODE=development it will look for .env.development file
If mode is not set, it will look for .env file in the root of your project

.env                # loaded in all cases
.env.local          # loaded in all cases (used as override for local development)
.env.[mode]         # only loaded in specified mode
.env.[mode].local   # only loaded in specified mode (used as override for local development)
# Example .env file content
MIGRATE_MONGO_URI=mongodb://localhost/my-db
MIGRATE_MONGO_COLLECTION=migrations
MIGRATE_CONFIG_PATH=./migrate
MIGRATE_MIGRATIONS_PATH=./migrations
MIGRATE_TEMPLATE_PATH=./migrations/template.ts
MIGRATE_AUTOSYNC=false
# or 
migrateMode=development
migrateMongoUri=mongodb://localhost/my-db
migrateMongoCollection=migrations
migrateConfigPath=./migrate
migrateMigrationsPath=./migrations
migrateTemplatePath=./migrations/template.ts
migrateAutosync=false
Config file .env / export Default Required Description
mode MIGRATE_MODE - No environment mode to use .env.[mode] file
uri MIGRATE_MONGO_URI - Yes mongo connection string
collection MIGRATE_MONGO_COLLECTION migrations No collection name to use for the migrations
configPath MIGRATE_CONFIG_PATH ./migrate No path to the config file
migrationsPath MIGRATE_MIGRATIONS_PATH ./migrations No path to the migration files
templatePath MIGRATE_TEMPLATE_PATH - No template file to use when creating a migration
autosync MIGRATE_AUTOSYNC false No automatically sync new migrations without prompt

Getting started with the CLI

yarn migrate help
npx migrate help
pnpm migrate help
CLI migration tool for mongoose

Options:
  -f, --config-path <path>      path to the config file (default: "migrate")
  -d, --uri <string>            mongo connection string
  -c, --collection <string>     collection name to use for the migrations (default: "migrations")
  -a, --autosync <boolean>      automatically sync new migrations without prompt (default: false)
  -m, --migrations-path <path>  path to the migration files (default: "./migrations")
  -t, --template-path <path>    template file to use when creating a migration
  --mode <string>               environment mode to use .env.[mode] file
  -h, --help                    display help for command

Commands:
  list                          list all migrations
  create <migration-name>       create a new migration file
  up [migration-name]           run all migrations or a specific migration if name provided
  down <migration-name>         roll back migrations down to given name
  prune                         delete extraneous migrations from migration folder or database
  help [command]                display help for command
  • Examples yarn
yarn migrate list -d mongodb://localhost/my-db
yarn migrate create add_users -d mongodb://localhost/my-db
yarn migrate up add_user -d mongodb://localhost/my-db
yarn migrate down delete_names -d mongodb://localhost/my-db
yarn migrate down # will rollback one migration
yarn migrate prune -d mongodb://localhost/my-db
yarn migrate list --config settings.json
  • Examples npm
npm run migrate list -d mongodb://localhost/my-db
npm run migrate create add_users -d mongodb://localhost/my-db
npm run migrate up add_user -d mongodb://localhost/my-db
npm run migrate down delete_names -d mongodb://localhost/my-db
npm run migrate down # will rollback one migration
npm run migrate prune -d mongodb://localhost/my-db
npm run migrate list --config settings.json
  • Examples pnpm
pnpm migrate list -d mongodb://localhost/my-db
pnpm migrate create add_users -d mongodb://localhost/my-db
pnpm migrate up add_user -d mongodb://localhost/my-db
pnpm migrate down delete_names -d mongodb://localhost/my-db
pnpm migrate down # will rollback one migration
pnpm migrate prune -d mongodb://localhost/my-db
pnpm migrate list --config settings.json

Options override order

Note that options are overridden in the following order:

  • Command line args > Env vars > Config file

Migration files

This example demonstrates how you can create a migration file using the CLI
By default, ts-migrate-mongoose assumes your migration folder exists (if it does not it will create one for you)

Here's an example of a migration created using:

yarn migrate create first-migration-demo
npx migrate create first-migration-demo
pnpm migrate create first-migration-demo

Executing the above command will create a migration file in the ./migrations folder with the following content:

  • 1673525773572-first-migration-demo.ts
// Import your models here

export async function up (): Promise<void> {
  // Write migration here
}

export async function down (): Promise<void> {
  // Write migration here
}

Using mongoose models in your migrations

As long as you can import the references to your models you can use them in migrations
Below is an example of a typical setup in a mongoose project:

  • models/User.ts - defines the User model
import { Schema, model, models } from 'mongoose'

interface IUser {
  firstName: string
  lastName?: string
}

const UserSchema = new Schema<IUser>({
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String
  }
})

export default models.User ?? model<IUser>('User', UserSchema)
  • models/index.ts - ensures that all models are exported and you establish a connection to the database
import mongoose from 'mongoose'
import mongooseOptions from '../options/mongoose'

import User from './User'

const getModels = async () => {
  // In case you using mongoose 6
  // https://mongoosejs.com/docs/guide.html#strictQuery
  mongoose.set('strictQuery', false)

  // Ensure connection is open so we can run migrations
  await mongoose.connect(process.env.MIGRATE_MONGO_URI ?? 'mongodb://localhost/my-db', mongooseOptions)

  // Return models that will be used in migration methods
  return {
    mongoose,
    User
  }
}

export default getModels
  • 1673525773572-first-migration-demo.ts - your migration file
import getModels from '../models'

export async function up () {
  const { User } = await getModels()
  // Write migration here
  await User.create([
    {
      firstName: 'John',
      lastName: 'Doe'
    },
    {
      firstName: 'Jane',
      lastName: 'Doe'
    }
  ])
}

export async function down () {
  const { User } = await getModels()
  // Write migration here
  await User.deleteMany({ firstName: { $in: ['Jane', 'John'] } }).exec()
}

Notes

  • Currently, the -d or --uri must include the database to use for migrations in the uri.
  • Example: -d mongodb://localhost:27017/development
  • If you don't want to pass it in every time feel free to use migrate.ts or migrate.json config file or an environment variable
  • Feel Free to check out the /examples folder in the project to get a better idea of usage in Programmatic and CLI mode

Check my other projects

ts-migrate-mongoose's People

Contributors

dependabot[bot] avatar ilovepixelart avatar snyk-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ts-migrate-mongoose's Issues

Support for the same database in multiple projects

Is your feature request related to a problem? Please describe.
Currently, when I use ts-migrate-mongoose in multiple projects to connect to the same database, the migrate files are distributed across different projects.
When I execute migrate up in project A, if there is a file in the database table that belongs to another project but has not been executed up, an error would occur, indicating that it cannot find the xxxxx file.

Describe the solution you'd like
The desired outcome is that the command execution is not interrupted regardless of the situation. Otherwise, I would need to specify different data tables in different projects, migrations-a and migrations-b. This would appear to be cumbersome.

Additional context
I hope my description is comprehensive enough. Can this functionality be supported?

Choose env.<local,dev,staging,prod>

Hi, I want to be able to do

NODE_ENV=production npx migrate up
NODE_ENV=dev npx migrate up
NODE_ENV=mycustomenv npx migrate up

You just have to do this :

// in getMigrator function
+  if (process.env['NODE_ENV']) {
+    config({ path: `.env.${process.env['NODE_ENV']}`, override: true })
+  }

you can keep config{ path : '.env' }) because its really usefull for default/shared variables

thx for the package, really helpful for me and my team <3

Want to be able work with centralized migration with multiple sub migration.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Duplicate identifier

Describe the bug
ts-migrate-mongoose conflicts with package mongoose

To Reproduce
Steps to reproduce the behavior:

  1. Use both ts-migrate-mongoose and mongoose packages (I have a nestjs project)

Lots of errors in the console like:

node_modules/ts-migrate-mongoose/node_modules/mongoose/types/virtuals.d.ts:11:10 - error TS2300: Duplicate identifier 'SchemaOptionsVirtualsPropertyType'.

11     type SchemaOptionsVirtualsPropertyType<DocType = any, VirtualPaths = Record<any, unknown>, TInstanceMethods = {}> = {
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/mongoose/types/virtuals.d.ts:11:10
    11     type SchemaOptionsVirtualsPropertyType<DocType = any, VirtualPaths = Record<any, unknown>, TInstanceMethods = {}> = {
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    'SchemaOptionsVirtualsPropertyType' was also declared here.

Expected behavior
ts-migrate-mongoose works with the mongoose package

Screenshots
Снимок экрана 2023-11-10 в 06 26 45

Desktop (please complete the following information):

  • OS: macOS Sonoma
  • Version 14.1

Additional context

  • mongoose 6.8.0
  • ts-migrate-mongoose 3.4.2

Unable to load custom TS aliases like `@/models`

Describe the bug

We're trying to use the default approach with yarn migrate up but inside our mongoose model files we're using typescript aliases configured in the projects' tsconfig.json and they are not getting resolved properly since ts-migrate-mongoose does not know about our custom paths.

// tsconfig.json

{
  "compilerOptions": {
      "target": "es2015",
      "paths": {
      "@/*": [
          "./*"
      ]
    }
  }
}
  
Synchronizing database with file system migrations...
Your application tried to access @, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

Required package: @ (via "@/mongo/models/thread.model")
Required by: /Users/kachar/Projects/my-project/migrations/

Require stack:
- /Users/kachar/Projects/my-project/migrations/1689246892881-test-migration-1.ts
- /Users/kachar/Projects/my-project/.yarn/cache/ts-migrate-mongoose-npm-3.1.8-c236e6134e-78a9407929.zip/node_modules/ts-migrate-mongoose/dist/cjs/migrator.js
- /Users/kachar/Projects/my-project/.yarn/cache/ts-migrate-mongoose-npm-3.1.8-c236e6134e-78a9407929.zip/node_modules/ts-migrate-mongoose/dist/cjs/commander.js
- /Users/kachar/Projects/my-project/.yarn/cache/ts-migrate-mongoose-npm-3.1.8-c236e6134e-78a9407929.zip/node_modules/ts-migrate-mongoose/dist/cjs/bin.js

We've tried to avoid the aliases inside the models but this has many complications all over the codebase.
We've also tried to use yarn patch to update the tsconfig.json of ts-migrate-mongoose but that didn't end up having any effect.

What worked for us was to have a version of migrate.ts in our codebase and use https://github.com/swc-project/swc-node to start it with our own tsconfig.json but with this approach, we can't use the CLI tool out of the box and we have to mirror the functionality.

"migrate:up": "node -r @swc-node/register ./migrations/index.ts up",
"migrate:down": "node -r @swc-node/register ./migrations/index.ts down",
"migrate:create": "node -r @swc-node/register ./migrations/index.ts create"

Unable to load environment variables from `.env.local`

Describe the issue
We're keeping our environment variables in file .env.local instead of .env and ts-migrate-mongoose is not picking them out of the box.

In order to load them we needed to manually invoke dotenv

// migrate.ts

import { config } from 'dotenv'

config({ path: '.env.local', override: true })

export default {
  uri: process.env.MIGRATE_MONGO_URI ?? 'mongodb://localhost:27017/test'
  // "collection": "migrations",
  // "migrationsPath": "./migrations",
  // "templatePath": "./migrations/template.ts",
  // "autosync": false
}

Do you plan to support similar functionality?

Using tsyringe in migration file

Is your feature request related to a problem? Please describe.
Hi! First I would like to thank you, I've just set up your lib in the project of my company, this is dope!
I came across an issue when using tsyringe in db migration files

import 'reflect-metadata';

import { UsersRepository } from '@modules/users/users.repository';

import { autoInjectable, container } from 'tsyringe';

@autoInjectable()
class Migration {
    constructor(private userRepo: UsersRepository) {}

    // eslint-disable-next-line no-empty-function
    async up() {
        const users = await this.userRepo.find({ filter: { }});
        console.log(users.length);
        console.log('Migration up usersssss');
    }

    // eslint-disable-next-line no-empty-function
    async down() {}
}

const migration = container.resolve(Migration);

export async function up(): Promise<void> {
    await migration.up();
}

export async function down(): Promise<void> {
    await migration.down();
}

but when I try to run the migrations, I have this error

npx migrate up -f .env.local

Synchronizing database with file system migrations...
Failed to run migration with name '1' due to an error
Cannot read properties of undefined (reading 'find')

It's like, it can't resolve the class with the depedencies (userRepo is undefined here)

maybe its due to

Describe alternatives you've considered
I've considered to just instanciate class and not using tsyringe but it would be awesome to be able to do this.

Possibly a problem with dynamic import

Describe the bug
Locally everything works well:

Снимок экрана 2023-11-22 в 06 37 25

But it doesn’t work in kubernetes:

Снимок экрана 2023-11-22 в 06 33 18

According to logs it gets stuck on dynamic import:

const migrationFunctions = await import(migrationFilePath) as IMigrationModule

What could be the problem?

And what do empty curly braces ({}) at the end of logs mean?

Additional context

  • ts-migrate-mongoose 3.4.1

v3.6.3 Client must be connected before running operations

Hello,

Since I installed v3.6.3 I got an error message when I run migrations against an Azure Cosmos DB for mongoDB:
.I have two migrations to run.
After the first one is up, I receive the error that say : "Client must be connected before running operations"
But when I am looking in the DB, the data are present.

I revert to v3.6.2.

image

commander.ts doesn't seem to pass the `connectOptions` forward

Describe the bug
commander.ts doesn't seem to pass the connectOptions forward.

To Reproduce

  1. Specify a connectOptions attribute in the migrate.ts
const connectOptions = {
  dbName: process.env.DB_NAME,
  tlsCAFile: 'global-bundle.pem',
};

export default {
  uri: process.env.DB_URI,
  collection: 'migrations',
  migrationsPath: './migrations',
  autosync: true,
  connectOptions,
};
  1. Try to create a migration
  2. It won't connect with the tlsCAFile specified;

Expected behavior
To connect using the provided tlsCAFile path.

Additional context
I'm using AWS Document DB and the tlsCAFile is mandatory to establish a connection.
I was able to get it to work doing the following:

// commander.ts
// ...
const connectOptions = fileOptions.connectOptions;
// ...
const migratorOptions = {
        migrationsPath,
        uri,
        collection,
        autosync,
        connectOptions, // Added the connectOptions here
        cli: true
    };

Importing `IOptions` interface externally

Thanks for the awesome lib! 🎉

While running the project using migrate.ts strategy we noticed the following eslint rule warning:

Assign object to a variable before exporting as module default eslint import/no-anonymous-default-export

image

While we can disable the rule locally we can also extract the config as a local variable and provide proper TS types for it.

The interface:

interface IOptions {
configPath?: string
uri?: string
collection?: string
autosync?: boolean
templatePath?: string
migrationsPath?: string
}

Expected implementation:

// migrate.ts
import type { IOptions } from 'ts-migrate-mongoose'

const migrateConfig: IOptions = {
  uri: "mongodb://localhost/my-db",
  collection: "migrations",
  migrationsPath: "./migrations",
  templatePath: "./migrations/template.ts",
  autosync: false,
}
export default migrateConfig

prune not pruning the migrations

Describe the bug
Hey! Thank you for providing this library!
I just started evaluating your package for our use case and tried the prune command, which is not working as I expected.

To Reproduce
Steps to reproduce the behavior:

  1. yarn migrate create test-migration
  2. The migration file is created and also added to the new migrations collection in my database, status "down" (see screenshot below)
  3. I wanted to remove it again by using: yarn migrate prune
  4. The comand runs without an error, but migration file and also the entry in the migrations collection is still there.

Expected behavior
Maybe my understanding of the prune command is wrong, but should't both, the migration file and also the entry in the migrations collections, be gone afterwards?

The detailed manual says something about options, I guess I need to define if it should be pruned from the db or from the database? What are the options to do so? :)

Screenshots
image

Additional context
I added a migrate.ts file with following settings:

export default {
  uri: process.env.MONGODB_CONNECTION_STRING,
  migrationsPath: './db/migrations',
  autosync: false,
};

Versions:

  • yarn v1.22.19
  • node v18.16.1
  • ts-migrate-mongoose v3.3.0
  • mongoose 6.10.5

Can't access models when running the package programmatically

Describe the bug
The following from npm does not work for me:
Screenshot 2023-05-03 112835

I get the following error:
TypeError: Failed to run migration with name 'add-middle-name' due to an error. this is not a function

This is my code:
file using migrator
Screenshot 2023-05-03 113922

schema file
Screenshot 2023-05-03 114008

migration function
Screenshot 2023-05-03 113827

Expected behavior
Should work as stated in npm.

Can't use library with esbuild

Describe the bug
my project uses esbuild which seems to be incompatible with swc

To Reproduce
Steps to reproduce the behavior:
install ts-express-swc in project that builds with esbuild, run build step to see following errors:
esbuild_swc_issuepng

Expected behavior
Will this library not work with projects that use esbuild? Is there a workaround for this?

Desktop (please complete the following information):

  • OS: Windows 11

Let me know if any additional context is needed.

Error on migrate up command

Describe the bug
Getting error Cannot use import statement outside a module when running the command npx migrate up.

To Reproduce
Steps to reproduce the behavior:

  1. Create a new npm typescript project
  2. Install ts-migrate-mongoose
  3. Run commands npx migrate create test and npx migrate up test
  4. See error text
Synchronizing database with file system migrations...
Cannot use import statement outside a module

Expected behavior
Run the migration test's up function code.

Screenshots

PS C:\test> npx migrate create test
Synchronizing database with file system migrations...
Created migration test in C:\test\migrations
Migration created. Run migrate up test to apply the migration
PS C:\test> npx migrate up test
Synchronizing database with file system migrations...
Cannot use import statement outside a module

Desktop:

  • OS: Windows 11 Home
  • Version 10.0.22621 Build 22621

MongoDB:

  • Device: Docker Kubernetes
  • Docker Image: mongo:4.0.23
  • Version: 4.0.23

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "ts-migrate-mongoose": "^2.4.2"
  },
  "devDependencies": {
    "@types/express": "^4.17.1",
    "typescript": "^4.9.4"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["es2015"]
}

compiling the migration file

Where is the migration ts files compiled? I only see register(swcrc) in your sources. At what stage does the compiler call occur?

runMigration() fails while importing the migration file using ESM

Describe the bug

The dynamic import in the migrator.ts line 411 const migrationFunctions = await import(migrationFilePath) as IMigrationModule fails with the following TypeError:

TypeError: Unknown file extension ".ts" for /migrations/1704814522221-test.ts at new NodeError (node:internal/errors:405:5) at 
Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11) at defaultGetFormat 
(node:internal/modules/esm/get_format:124:36) at defaultLoad (node:internal/modules/esm/load:84:20) at nextLoad
 (node:internal/modules/esm/loader:163:28) at ESMLoader.load (node:internal/modules/esm/loader:603:26) at 
ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22) at new ModuleJob 
(node:internal/modules/esm/module_job:64:26) at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17) at 
ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {code: "ERR_UNKNOWN_FILE_EXTENSION", stack: 
"TypeError: Unknown file extension ".ts" for /Users…duleJob (node:internal/modules/esm/loader:434:34)", message: "Unknown file 
extension ".ts" for /Users/stephan/Do…object-pool-data/migrations/1704814522221-test.ts", toString: Function, 
Symbol(kIsNodeError): true}

To Reproduce
Create a new migration using the CLI in an nestJS application in ESM
Start the nestJS Service with the on startup migration functionality in place.

Expected behavior
The dynamic import should also handle the migration files in ESM mode by rewriting the ts file-ending to .js

ESM problem with wrong export * as IOptions from './interfaces/IOptions';

Describe the bug
While using the package as ESM within nestJS, I run into a problem in the ts-migrate-mongoose/esm/migrator.js file in line 11.
export * as IOptions from './interfaces/IOptions';

The detailed error message:

Error: Cannot find module '/xyz/node_modules/ts-migrate-mongoose/dist/esm/interfaces/IOptions' imported from /xyz/node_modules/ts-migrate-mongoose/dist/esm/migrator.js
    at new NodeError (node:internal/errors:405:5)
    at finalizeResolution (node:internal/modules/esm/resolve:324:11)
    at moduleResolve (node:internal/modules/esm/resolve:943:10)
    at defaultResolve (node:internal/modules/esm/resolve:1129:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:835:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36)

To Reproduce
Add the ts-migrate-mongoose package in your ESM NestJS projects package.json
Try to run migrations at NestJS service startup.

Expected behavior
ts-migrate-mongoose/bash
/esm.sh
should add the missing '.js'-file-ending for the export pattern used in ts-migrate-mongoose/esm/migrator.js file in line 11 so that this line ends up like export * as IOptions from './interfaces/IOptions.js';

swcrc module type

Describe the bug
I can't use es6 imports in migration files in production (via kubernetes). But locally it works well.

I wrapped the dynamic import (const migrationFunctions = (await import(migrationFilePath)) as IMigrationModule) in try-catch and this is the error in the logs:

/opt/nest-api/migrations/1699935100948-drop-orders.ts:1
import * as mongoose from 'mongoose';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Object.newLoader [as .ts] (/opt/nest-api/node_modules/pirates/lib/index.js:104:7)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Function.Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at /opt/nest-api/src/ts-migrate-mongoose/migrator.ts:519:28
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at Migrator.runMigrations (/opt/nest-api/src/ts-migrate-mongoose/migrator.ts:518:31)
at Migrator.run (/opt/nest-api/src/ts-migrate-mongoose/migrator.ts:209:27)
at runMigrations (/opt/nest-api/src/migrator.ts:45:3)
at AppBootstrap.bootstrap (/opt/nest-api/src/main.ts:118:5)

Why are you using type: 'commonjs' and not type: 'es6' in swcrc.ts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.