使用 mikro-orm 和 typescript 创建类实例并将其插入 postgresql 数据库时出现问题

Oli*_*via 1 postgresql node.js typescript mikro-orm postgresql-14

我正在尝试按照此React GraphQL TypeScript 教程进行编码

该项目使用 MikroOrm 与 PostgreSQL 数据库进行通信。

目标:创建一个 post 实例并将其插入数据库。

目前我在 19.53 分钟,遇到了以下错误,该错误没有出现在视频中,我不知道为什么。

Post.ts 文件:

@Entity() //correspond to database table.
export class Post {
    @PrimaryKey()
    id!: number;

    @Property({ type: 'date'}) //denote database column, without it its just a class attribute
    createdAt = new Date();

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

    @Property({type: 'text'})
    title!: string;
}
Run Code Online (Sandbox Code Playgroud)

Index.ts 文件:

const main = async () => {
    const orm = await MikroORM.init(microConfig);
    const post = orm.em.create(Post, {title: "my first post" }); //create instance of post
    await orm.em.persistAndFlush(post); //insert into database
}
Run Code Online (Sandbox Code Playgroud)

Index.ts 中的行向我抛出一个错误:

const post = orm.em.create(Post, {title: "my first post" });
Run Code Online (Sandbox Code Playgroud)
Argument of type '{ title: string; }' is not assignable to parameter of type 'RequiredEntityData<Post>'.
  Type '{ title: string; }' is missing the following properties from type '{ createdAt: EntityDataItem<Date>; updatedAt: EntityDataItem<Date>; title: EntityDataItem<string>;
Run Code Online (Sandbox Code Playgroud)

Mar*_*mek 8

v6 添加了一种新的方法来处理这个问题,即Opt类型,您可以简单地将其与属性定义相交。这主要对基本实体很有帮助,因此您不必处理符号的泛型OptionalProps

https://mikro-orm.io/docs/next/guide/relationships#alternative-approach-with-opt-type

@Entity()
export class Post {
    @PrimaryKey()
    id!: number;

    @Property()
    createdAt: Date & Opt = new Date();

    @Property({ onUpdate: () => new Date() })
    updatedAt: Date & Opt = new Date();

    @Property({ type: 'text' })
    title!: string;
}
Run Code Online (Sandbox Code Playgroud)

您需要通过OptionalProps符号标记具有初始值设定项的属性,以使它们对于该em.create()方法是可选的。另外,type您可以只显式指定类型,而不是显式选项(推理不适用于反射元数据)。

https://mikro-orm.io/docs/property-validation#properties-with-default-value

这是一个应该可以正常工作的实体定义:

@Entity()
export class Post {
    [OptionalProps]?: 'createdAt' | 'updatedAt';

    @PrimaryKey()
    id!: number;

    @Property()
    createdAt: Date = new Date();

    @Property({ onUpdate: () => new Date() })
    updatedAt: Date = new Date();

    @Property({ type: 'text' })
    title!: string;
}
Run Code Online (Sandbox Code Playgroud)