NodeJS typeORM在数据库架构中未找到任何更改-无法生成迁移,要创建新的空迁移,请使用“typeorm migration:create”命令

beq87vna  于 2023-03-29  发布在  Node.js
关注(0)|答案(5)|浏览(161)

我正在做一个课程,我们正在使用express-node postgres和react(使用typescript)和typeORM。到目前为止,一切都运行良好,但我面临着typeORM的问题,我不知道发生了什么,为什么会发生这个错误

大问题:所以,问题是,我正在进行身份验证,在某个时候我们更改了数据库中的用户模式,因此我们必须进行迁移,但是,在迁移之前,我们执行了npm run typeorm schema:drop,但是当我尝试时,迁移发生了这种情况

这是我使用的第一个命令

npm run typeorm migration:generate -- --n create-users-table

这就是错误

> new-typeorm-project@0.0.1 typeorm C:\Users\diego cifuentes\Desktop\Studying  Backend\redit> ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"

bin.js migration:generate

Generates a new migration file with sql needs to be executed to update
schema.

Opciones:
  -h, --help          Muestra ayuda                             [booleano]  -c, --connection    Name of the connection on which run a query.
                                                      [defecto: "default"]  -n, --name          Name of the migration class.
                                        [cadena de caracteres] [requerido]  -d, --dir           Directory where migration should be created.
  -p, --pretty        Pretty-print generated SQL
                                               [booleano] [defecto: false]  -f, --config        Name of the file with connection configuration.
                                                    [defecto: "ormconfig"]  -o, --outputJs      Generate a migration file on Javascript instead of
                      Typescript               [booleano] [defecto: false]      --dr, --dryrun  Prints out the contents of the migration instead of
                      writing it to a file     [booleano] [defecto: false]      --ch, --check   Verifies that the current database is up to date and                      that no migrations are needed. Otherwise exits with
                      code 1.                  [booleano] [defecto: false]  -v, --version       Muestra número de versión                 [booleano]
Falta argumento requerido: n
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! new-typeorm-project@0.0.1 typeorm: `ts-node ./node_modules/typeorm/cli.js "migration:generate" "create-users-table"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the new-typeorm-project@0.0.1 typeorm script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\diego cifuentes\AppData\Roaming\npm-cache\_logs\2021-05-11T15_29_02_081Z-debug.log

经过几个小时的尝试到处寻找解决方案,我将最后一个命令更改为以下命令

npx typeorm migration:generate -- --n create-users-table

这次的错误是不同的,看起来像这样

No changes in database schema were found - cannot generate a migration. To create a new empty migration use "typeorm migration:create" command

所以,我说,好吧,我越来越接近解决这个问题,但是...经过几个小时(再次)寻找一个新的答案,我找不到任何东西,所以,我需要写这篇文章来解决我的问题。所以现在,让我向你展示我的ormconfig,我的package.json和我想在postgres DB中迁移的实体。
package.json(脚本typeorm在最后)

{
  "name": "new-typeorm-project",
  "version": "0.0.1",
  "description": "Awesome project developed with TypeORM.",
  "devDependencies": {
    "@types/bcrypt": "^5.0.0",
    "@types/cookie": "^0.4.0",
    "@types/cookie-parser": "^1.4.2",
    "@types/express": "^4.17.11",
    "@types/jsonwebtoken": "^8.5.1",
    "@types/morgan": "^1.9.2",
    "@types/node": "^15.0.2",
    "morgan": "^1.10.0",
    "nodemon": "^2.0.7",
    "ts-node": "^9.1.1",
    "typescript": "^4.2.4"
  },
  "dependencies": {
    "bcrypt": "^5.0.1",
    "class-transformer": "^0.4.0",
    "class-validator": "^0.13.1",
    "cookie": "^0.4.1",
    "cookie-parser": "^1.4.5",
    "dotenv": "^9.0.1",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "pg": "^8.4.0",
    "reflect-metadata": "^0.1.10",
    "typeorm": "0.2.32"
  },
  "scripts": {
    "start": "ts-node src/server.ts",
    "dev": "nodemon --exec ts-node src/server.ts",
    "typeorm": "ts-node ./node_modules/typeorm/cli.js"
  }
}

ormconfing.json备注:我将实体、迁移和订阅者更改为.js,因为.ts总是给我错误。

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "**",
  "password": "**",
  "database": "**",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entities/**/*.js"],
  "migrations": ["src/migrations/**/*.js"],
  "subscribers": ["src/subscribers/**/*.js"],
  "cli": {
    "entitiesDir": "src/entities",
    "migrationsDir": "src/migrations",
    "subscribersDir": "src/subscribers"
  }
}

最后我想展示的是,尽管它可能不是那么重要,这是用户模式

import {
  Entity as TOEntity,
  Column,
  Index,
  BeforeInsert,
  OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";

import Entity from "./Entity";
// import Post from "./Post";

@TOEntity("users")
export default class User extends Entity {
  constructor(user: Partial<User>) {
    super();
    Object.assign(this, user);
  }

  @Index()
  @IsEmail()
  @Column({ unique: true })
  email: string;

  @Index()
  @Length(3, 200)
  @Column({ unique: true })
  username: string;

  @Exclude()
  @Length(6, 200)
  @Column()
  password: string;

  // @OneToMany(() => Post, post => post.user)
  // posts: Post[];

  @BeforeInsert()
  async hashedPassword() {
    this.password = await bcrypt.hash(this.password, 6);
  }
}

最终目标:所以,如果你能帮我这个,你会保存我的命.最后一件事是,我试图张贴我的问题首先在西班牙语网站的堆栈溢出,但没有人可以帮助我,所以也许有人会在这里,感谢您的时间和照顾!

x9ybnkn6

x9ybnkn61#

entitiesmigrationssubscribers更改为dist目录。
例如:

entities: ["dist/entities/**/*{.js,.ts}"],
  migrations: ["dist/migrations/**/*{.js,.ts}"],
  subscribers: ["dist/subscribers/**/*{.js,.ts}"],

dist目录是构建应用程序时创建的目录。您可以使用tsconfig.json-〉compilerOptions-〉outDir找到dist目录。
然后使用npm run build再次构建您的应用,并尝试生成迁移。

rta7y2nd

rta7y2nd2#

对于我来说ormconfig.json是这样的,

"entities": [
      "dist/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],

将其更改为

"entities": [
      "src/entity/**/*{.js,.ts}"
   ],
   "migrations": [
      "src/migration/**/*{.js,.ts}"
   ],
   "subscribers": [
      "src/subscriber/**/*{.js,.ts}"
   ],

已正确生成迁移。
json脚本类似于“typeorm”:“node --require ts-node/register ./node_modules/typeorm/cli.js”
而使用的命令是
npm run typeorm migration:generate -- -n FileAddTemporaryDeletedFields -p --dr --ch

icnyk63a

icnyk63a3#

我看到过这个错误,如果我没有弄错的话,那是因为我试图创建一个已经创建的银行。

以下命令删除所有表:

yarn typeorm query "DROP SCHEMA public CASCADE; CREATE SCHEMA public; GRANT USAGE ON SCHEMA public to PUBLIC; GRANT CREATE ON SCHEMA public to PUBLIC; COMMENT ON SCHEMA public IS 'standard public schema';"

则:

yarn typeorm --migration:generate -n migration_name -d path/to/your/migrations/

1aaf6o9v

1aaf6o9v4#

据我所知,ormconfig.json在最新版本中已被弃用。但无论如何,我将在使用旧版本时分享我的解决方案。
生成时,typeorm首先读取ormconfig.json并登录到rdbms中。并在'the actual schema of db'和'schema file as ormconfig.json [entities]'之间进行比较
所以,如果文件(写在ormconfig.json中的'entities')在dist文件夹中.你必须编辑那个.js文件.(不是src文件夹中的.ts文件)
但是,如果'entities'文件在src文件夹中作为ormconfig.json,检查vscode的'autosave'功能是否打开。如果你'npm run start:dev'可能是这样的情况,在你编辑实体文件之前,db的实际模式已经被修改了。

w1jd8yoj

w1jd8yoj5#

我遇到过这个问题。它无法读取给定路径的实体,我认为问题的发生是由于文件权限问题或其他原因。

所以我改变了

entities: ['src/app/entities/*{.ts,.js}']

entities: [Role,User]

它工作正常,不要忘记导入您的实体,如

import { Role } from '../entities/role.entity';
import { User } from '../entities/user.entity';

相关问题