【问题标题】:TypeORM bulk create with relationsTypeORM 批量创建与关系
【发布时间】:2019-12-02 16:50:34
【问题描述】:

有没有办法插入大量数据而不会耗尽 JS 堆内存?我有一个电子邮件模型,如下所示:

@Entity("email")
export class Email extends BaseEntity {

    @PrimaryGeneratedColumn()
    public id: number;

    @ManyToOne((type) => Category, (cat) => cat.category, {nullable: false, cascade: ['insert']})
    public category: Category;

    @Column({type: "text", name: "email"})
    public email: string;

}

和类别:

@Entity("category")
export class Category extends BaseEntity {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column({type: "text", name: "category"})
    public category: string;

    @OneToMany((type) => Email, (email) => email.category, {nullable: true})
    public emails: Email[];

}

我遇到的第一个问题是,当我尝试保存 {email: 'blabal@blalbah.com', category: 'default'} 时,它说类别必须是一个 ID,但问题是我想添加电子邮件并创建类别(如果它不存在)或将 ID 分配给电子邮件如果它存在。我做了以下代码:

 public async bulkCreate(emails: Email[]): Promise<any> {
        try {
            const emailRepo = await getRepository(Email);
            const categoryRepo = await getRepository(Category);
            await Promise.all(emails.map(async (mail) => {
                const cat = await categoryRepo.findOne({where: {category: mail.category}});
                if (cat) {
                    // @ts-ignore
                    mail.category = cat.id;
                } else {
                    const newCat = await categoryRepo.save(Object.assign(new Category(), mail));
                    // @ts-ignore
                    mail.category = newCat.id;
                }
                await emailRepo.save(mail);
            }));
        } catch (e) {
            console.log(e);
            throw new Error(e);
        }
    }

处理了几封电子邮件,但是当我尝试添加时,即使只有 1,000 个内存也会上升到 Like 4Gig,然后就崩溃了。

我该怎么办?我想一次添加 1,000 多封电子邮件。

【问题讨论】:

    标签: mysql typescript typeorm


    【解决方案1】:

    我知道这有点晚了,但这个解决方案使用Bluebird Promise.map,所以你可以定义并发。而是一次性执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多