Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM

The Test entity is defined below:

export class Test {
   @PrimaryColumn('integer')
   id: number;
 
   @Column('varchar', { length: 255 })
   testName: string;
 }

I have the following objects that I want to insert in batch:

const test1 = new Test();
script.id = 1;
script.testName = 't1';

const test2 = new Test();
test2.id = 2;
test2.testName = 't2';

const test3 = new Test();
test3.id = 3;
test3.testName = 't3';

const tests = [test1, test2, test3];

However, when I attempt to save them together like this:

const testRepository = dataSource.getRepository(Test);
await testRepository.save(tests);

It doesn't work as expected. Strangely enough, testRepository.save(test1); works fine.

Can you guide me on how to perform a batch insert, especially when dealing with thousands of rows?

Answer №1

When utilizing TypeORM, the insert method is handy for executing bulk inserts.

To perform a bulk insert, you can follow this basic syntax:

const dataRepository = dataSource.getRepository(Data);

await dataRepository.insert(dataEntries);

Some key points to keep in mind:

  • The insert method accepts an array of entity objects
  • If your database requires explicit ids (like postgres), make sure the primary keys/ids are populated for each entity
  • In databases supporting auto-increment ids (such as sqlite, mysql), omitting ids is acceptable

For instance:

const dataEntries = [
  { id: 1, entryName: 'entry1'},
  { id: 2, entryName: 'entry2'}, 
  { id: 3, entryName: 'entry3'} 
];

await dataRepository.insert(dataEntries);

This code snippet will insert all 3 data entries in one go.

Additional suggestions include:

  • You have the flexibility to mix existing and new entities within the array
  • Split huge batches into chunks to avoid hitting query size limitations
  • Employing transactions can ensure atomicity during inserts

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

Verify the length of an array within an object using JavaScript

I am facing a problem with an object. Here is what it looks like: const array = { "entities": [ { "annexes": [ { "buildingUniqueIds": [] }, { ...

What is the best way to change `props.children` into a JSX element?

When using React functional components, we have the ability to render children in the following way: import React from 'react'; const MyComponent = (props: React.PropsWithChildren) => { return props.children; } However, I encountered an ...

Obtain the appropriate selection in the dropdown based on the model in Angular

I am working on a dropdown menu that contains numbers ranging from 1 to 10. Below is the HTML code for it: <div class="form-group"> <label>{{l("RoomNumber")}}</label> <p-dropdown [disab ...

API endpoint generating a Vue component as a rendered output

In the process of developing a document templater service, I am faced with the challenge of handling numerous document templates (contracts, protocols, etc.) written in Vue. The concept revolves around clients sending props in the body, which are then pass ...

Is it recommended to keep Angular properties private and only access them through methods?

I'm starting to get a bit confused with Angular/Typescripting. I originally believed that properties should be kept private to prevent external alteration of their values. Take this example: export class Foo{ private _bar: string; constructor(pr ...

Encountering issues with Proxy functionality in the latest versions of Angular 13 and Spring Boot

I've encountered an issue with the proxy configuration in Angular. I'm unsure if it's a problem within my Angular settings or if there's a configuration issue in Spring. For testing purposes, I have a backend built in springboot to han ...

What is the resolution if I need to utilize a property that is untyped?

Transitioning to TypeScript from plain old JavaScript is a step I'm taking because I believe it offers significant advantages. However, one drawback that has come to light is that not all attributes are typed, as I recently discovered. For instance: ...

add headers using a straightforward syntax

I'm attempting to append multiple header values. This is what I'm currently doing: options.headers.append('Content-Type', 'application/json'); options.headers.append('X-Requested-By', 'api-client'); ... ...

What is preventing TypeScript from automatically inferring the type of an argument in a generic function that utilizes `keyof`?

What causes the error in this code snippet? type MyType = { a: string, b: string } function cantInfer<In, Out>(fn: (i: In) => Out, i: In) { } function myFunction<K extends keyof MyType>(key: K): string { return ''; } ...

Angular CodeMirror Line-Break function not displaying line numbers

I am currently utilizing Code Mirror from ngx-codemirror. My goal is to split the line when it fits within the width of the parent container. After searching, I found a couple of solutions that suggest using: lineWrapping: true Additionally, in the styles ...

Specialized type for extra restriction on enum matching

In my current project, I am dealing with two enums named SourceEnum and TargetEnum. Each enum has a corresponding function that is called with specific parameters based on the enum value. The expected parameter types are defined by the type mappings Source ...

Troubleshooting Node.js import module errors

I have just discovered two files that I created using the TS language specification manual (on page 111). The first file, called geometry.ts, contains the following code: export interface Point { x: number; y: number }; export function point(x: number, y ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

Issue encountered with express-jwt and express-graphql: TypeScript error TS2339 - The 'user' property is not found on the 'Request' type

Implementing express-jwt and graphql together in typescript has been a challenge for me. import * as express from 'express' import * as expressGraphql from 'express-graphql' import * as expressJwt from 'express-jwt' import s ...

"Encountering issues with DefinePlugin when using the combination of Ionic, Angular, Webpack,

I'm trying to incorporate my process.env variable into the webpack Bundle using DefinePlugin. Here's the snippet of code in my webpack config: plugins: [ new webpack.DefinePlugin({ 'process.env': JSON.stringify(process.env) ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

Using the as operator in TypeScript for type casting a string

function doSomething(a : any) { let b = (a as Array<any>) alert(typeof b) // displays "string" } doSomething("Hello") The alert is showing "string" instead of what I anticipated, which was something along the lines of a null value. The docu ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

Leveraging Global Variables and Functions with Webpack and TypeScript

I have been utilizing Webpack in conjunction with TypeScript, HTML, and SCSS to develop a project. My goal is to create a single page application that incorporates a router located within the root folder of the project /framework/, with all my source code ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...