【发布时间】: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