Creating multiple records in TypeORM with relationships in bulk

Is there a way to efficiently insert a large amount of data without overwhelming the JS heap memory? I have a model for Email and Category as shown below:

@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;

}

and Category :

@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[];

}

The issue arises when attempting to save an email record with

{email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfada3aeadaea38fada3aea3adaea7e1aca0a2">[email protected]</a>', category: 'default'}
, triggering an error stating that Category must be an ID. My objective is to add emails and create the corresponding category if it does not already exist, or assign the existing category's ID to the email. Here is the code snippet:

 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);
        }
    }

This approach worked for a limited number of emails, but memory usage spikes significantly when processing around 1,000 records, leading to system crashes.

What steps can be taken to address this issue so that more than 1,000 emails can be added at once?

Answer №1

Although it may be slightly delayed, a potential solution for this issue is to utilize Bluebird Promise.map. This allows you to set the concurrency level for more efficient execution instead of running all operations in one go.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2 - The Iterable Differ fails to detect changes

I am currently utilizing the Iterable Differs feature in Angular2 to monitor changes in my data. However, I am facing an issue where the differ.diff method always returns "null" and I am unsure of the reason behind this. constructor(differs: IterableDiffe ...

Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play. AuthModule is responsible for importing the UserModule, which conta ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Incorporate a New Feature into my NPM Package

I've been searching high and low for an answer to this, but I'm still stuck. I'm working on a module in Angular 2 with ng-module, and everything is functioning properly. However, I'm struggling to assign a property to another property w ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...

Saving automatically using ajax, php, and mysql databases

I attempted to create a script that combines elements from the internet in order to automatically save form data to a MySQL database. However, something seems to have gone awry as the script is able to insert new rows every 20 seconds but fails to update t ...

The date selector is failing to accurately reflect changes in the date objects

I've integrated a date-time picker from this source https://github.com/DanielYKPan/date-time-picker to manage 'beginning' and 'end' date objects (refer to selectedMoments in the TypeScript code) for a date selector. However, when I ...

Facing issues with Laravel's php artisan telescope:install command not correctly publishing the assets

I am working on a Laravel 6 app and trying to integrate Telescope. I have followed all the necessary steps such as running `composer update` and `composer dump-autoload`, then installing Telescope. Everything seemed to be going smoothly until I ran `php ar ...

Exploring the representation of recursive types using generic type constraints

Is there a way to create a structure that can handle recursive relationships like the one described below? I am looking to limit the types of values that can be added to a general container to either primitive data types or other containers. Due to limit ...

The error message "PDOException: driver not found" indicates that the driver needed

Whenever I try to connect to a MySQL database on localhost using PHP, I encounter a PDOException stating that the driver could not be found. $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $thi ...

What could be causing the issue with my connection.query when using mysql in node.js?

Purpose: The goal is to perform a basic query on the database. Expected Outcome: The console should display "please print something!" along with the results of the query. Actual Outcome: Sadly, nothing appears on the terminal screen. Issues: No error me ...

What is the best way to retrieve TemplateRef from an Angular component?

TS Component ngOnInit() { if(somecondition) // The line of code that is causing issues this.openModal(#tempName); } HTML Component <ng-template #tempName> Content goes here! </ng-template> this.openModal(#tempNa ...

Dividing Query Outcomes by Weeks

Currently, I am in the process of developing a compact website to monitor diverse information using PHP and MYSQL. My goal is to set up a summary page that categorizes the data into weekly segments dynamically since this project will be ongoing for an ex ...

Query the MySQL database to fetch certain rows that are linked with keys stored in another table

I am a beginner with MySQL, so let me explain my issue using an example... I currently have two tables: Table1: +----+-----+-----+-----+-----+ | id | a1 | b1 | c1 | d1 | +----+-----+-----+-----+-----+ | 1 | ... | ... | ... | ... | | 2 | ... | .. ...

Using PDO prepared statements with the flexibility of optional parameters

Having some challenges with PDO and working on the API call for search results. How can I create a prepared statement with 2 optional parameters for the search query? $app->get('/get/search', function () { $sql = 'SELECT * FROM user ...

Error in Angular-CLI and TypeORM: Module parsing failed due to the presence of 'import' and 'export' statements, which are only allowed with 'sourceType: module'

When attempting to integrate typeorm into a new angular-cli project, I encounter a compiler error as soon as I reference typeorm. ./node_modules/typeorm/browser/index.js:3:0 - Error: Module parse failed: 'import' and 'export' may appear ...

What happens when you encounter a blank page while using mysqli_query()?

My new project involves creating a song recommendation website, and I've set up a form that directs to a page containing the following code: <?php ini_set('display_errors',1); ob_start(); session_start(); ...

Sundays and last days are excluding React-big-calendar and dayjs longer events from being displayed

I've encountered a bug in my calendar view implementation. Long events are not displaying on Sundays or the ending day. Please refer to this image for reference: https://i.stack.imgur.com/V0iis.png Event details: Start time: Mon Aug 07 2023 15:44:00 ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

Ways to tally distinct rows

SELECT HOUR(`Timestamp`) AS HOUR, COUNT(*) AS Alarms FROM `alarms` WHERE `Siteindex` IN ('4, 5, 8, 10, 11, 15') AND `Datestamp` = '2012-11-07' GROUP BY HOUR (`Timestamp`); This query is designed to display the coun ...