NodeJS 如何使用typeorm自动插入嵌条?

y1aodyip  于 2022-12-26  发布在  Node.js
关注(0)|答案(1)|浏览(183)

我是typeorm的新手。我已经在实践中完成了很多部分。但是现在我面临着困惑,因为我没有得到任何关于在typeorm中通过标题创建和更新唯一的slug的文档或博客。在mongoDB中,我们得到了一个mongoose-slug-updater来自动创建和更新slug。但是在typeorm中,我没有得到任何类似的东西。
我在用

typeorm (0.3.11)
Postgre (pg- 8.8.0)
Nestjs (9.0.0)

这是我的博客实体-

@Entity()
export class Blog {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    slug: string;
    @Column({ type: "text", nullable: false })
    title: string;
    @Column({ type: "text", nullable: false })
    body: string;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;
}

我怎么能自动创建和更新独特的鼻涕虫。请帮助我的人。

oxf4rvwz

oxf4rvwz1#

TypeORM没有任何现成的包,如mongoose-slug-updater。要创建slug,您可以使用@BeforeInsert()@BeforeUpdate()实体侦听器。您可以创建自己的slug生成逻辑或使用包,如slugify

const slugify = require('slugify')

@Entity()
export class Blog {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    slug: string;
    @Column({ type: "text", nullable: false })
    title: string;
    @Column({ type: "text", nullable: false })
    body: string;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;
    
    @BeforeInsert()
    @BeforeUpdate()
    generateSlug() {
      this.slug = slugify(this.title, { lower: true });
    }
}

要使slug唯一,您可以在slug后面添加一个随机数或异步签入。

this.slug = slugify(this.title, { lower: true }) + '-' +  RANDOM_STRING_GENERATING_FUNCTION

相关问题