mikro-orm 迁移未反映在 postgresql 中

问题描述

这是用户实体:

import { Entity,PrimaryKey,Property } from "@mikro-orm/core";
import { ObjectType,Field } from "type-graphql";

@ObjectType()
@Entity()
export class User {
  @Field()
  @PrimaryKey()
  id!: number;

  @Field(() => String)
  @Property({ type: "date" })
  createdAt = new Date();

  @Field(() => String)
  @Property({ type: "date",onUpdate: () => new Date() })
  updatedAt = new Date();

  @Field()
  @Property({ type: "text",unique: true })
  username!: string;

  @Field()
  @Property({ type: "text",unique: true })
  email!: string;

  @Property({ type: "text" })
  password!: string;
}

这是迁移脚本:

"create:migration": "mikro-orm migration:create"

我已经有了用户名和密码列,但是当我尝试添加“电子邮件”列时,迁移运行成功,但没有反映在数据库中。这是迁移结果:

export class Migration20210608151159 extends Migration {

  async up(): Promise<void> {
    this.addsql('alter table "user" add column "email" text not null;');
    this.addsql('alter table "user" add constraint "user_email_unique" unique ("email");');
  }

}

我刷新了表格但看不到电子邮件列。当我发送客户端请求时,我收到此错误

 error: insert into "user" as "e0" ("created_at","email","password","updated_at","username") values ($1,$2,$3,$4,$5) returning * - column "email" of relation "user" does not exist

当我这次运行 npx mikro-orm migration:up 时,我收到此消息:

"DriverException: alter table "user" add column "email" text not null; - column "email" of relation "user" already exists" 

不知何故迁移并没有修改数据库

解决方法

您刚刚创建了迁移,现在您需要通过 mikro-orm migration:up 运行它。

npx mikro-orm migration:create   # Create new migration with current schema diff
npx mikro-orm migration:up       # Migrate up to the latest version
npx mikro-orm migration:down     # Migrate one step down
npx mikro-orm migration:list     # List all executed migrations
npx mikro-orm migration:pending  # List all pending migrations

https://mikro-orm.io/docs/migrations/#using-via-cli

,

我找到了解决方法。我们可能正在学习 ben awad 的相同教程。我所做的是从 postgres 数据库中删除整个 User 表。然后我从 index.ts 注释掉了以下命令。

//await orm.getMigrator().up()

后来我删除了所有以前的迁移。

然后我在终端输入:

npx mikro-orm migration:create

然后:

npx mikro-orm migration:validate

为了确保即将实施正确的迁移

然后:

npx mikro-orm migration:up

在我看来,迁移器和迁移问题似乎存在问题。我还没有使用自动迁移工具 orm.getMigrator().up() 但我以后可能会再试一次

,

确保 User 实体列在 options.entities 文件内的 mikro-orm.config.js 中。