Failure of Cascading Insert Operation in TypeORM

I currently have a parent entity called CostCenter, which contains an Array of Coordinators. The attribute

coordinators: Array<Coordinator>
in the CostCenter class has typeORM annotations specified as follows:

export class CostCenter {
...
@OneToMany(() => Coordinator, (coordinator) => coordinator.costCenter, {
    eager: true,
    cascade: ['insert', 'update'],
  })
  coordinators: Array<Coordinator>;
...
}

The Coordinator class is defined as:

export class Coordinator {
...
  @ManyToOne(() => CostCenter, (costCenter) => costCenter.coordinators, {
    cascade: ['insert', 'update'],
  })
  costCenter: CostCenter;
...
}

I am facing an issue while trying to save a CostCenter along with its array of coordinators. The code snippet for this operation is given below:

async create(createCostCenterDto: CreateCostCenterDto) {
    const costCenter = new CostCenter(
      createCostCenterDto.code,
      createCostCenterDto.description,
      createCostCenterDto.id,
    );

    var coordinators = new Array<Coordinator>();
    await createCostCenterDto.coordinators.forEach((coordinator) => {
      coordinators.push(
        new Coordinator(
          coordinator.name,
          coordinator.email,
          coordinator.password,
          coordinator.id,
          coordinator.telephone,
          coordinator.registration,
          coordinator.course,
          coordinator.graduation,
        ),
      );
      this.coordinatorRepository.save(coordinator);
    });

    costCenter.coordinators = coordinators;
    return this.costCentersRepository.insert(costCenter);
  }

Despite following the typeORM documentation's instructions on cascades (), the code seems to have an issue where the coordinators are not properly linked to their corresponding costCenter entities. Even after trying different approaches like commenting out certain lines, the desired behavior was not achieved.

If anyone could provide assistance or suggestions on improving this functionality, it would be greatly appreciated.

Answer №1

TypeORM differentiates between low-level methods that handle basic SQL commands and higher-level functions that also handle cascading operations.

For example, the save method triggers cascade, unlike the insert method.

According to the documentation:

/**
* Inserts a given entity into the database.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT query.
* Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
*/
insert(entity: QueryDeepPartialEntity | (QueryDeepPartialEntity[])): Promise;

A similar distinction can be seen between the repository's remove and delete methods.

In your specific scenario, when trying to cascade insert coordinators while adding a new CostCenter to the database, it is recommended to use the repository's .save() method instead of .insert().

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

Error: Unable to execute fields.map function while generating a dynamic sitemap using next-sitemap module

I'm in the process of creating a dynamic sitemap for my website and here's the code I'm using: import { GetServerSideProps } from 'next'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { makeSl ...

Exclude the bundled .d.ts files and opt for external declarations instead

I am endeavoring to implement the validate.js library, which comes with its own TypeScript declaration file. However, the provided typing for the library is not very accurate, and there is a more superior one available in DefinitelyTyped. Despite installi ...

What could be causing the Angular/TypeScript model that I imported to fail to properly map to my service within my Angular application?

Struggling with implementing a system for manual entry of mutual fund information, I am running into errors when trying to read properties from the 'fund' model in my application. The Developer Tools console is displaying the following error mess ...

Transferring data from a child component to a parent using EventEmitter and dynamic components in Angular 6

Hey there, I am currently working on a dynamic form utilizing a dynamic component loader. The parent component structure is as follows: <div class="item-form-block-content"> <div class="form-block"> <ng-template pf-host></n ...

Encountering Angular Material UI issues following the transition from version 11 to 12

I am currently in the process of updating my Angular application from version 11 to 12, integrating Angular Material, and encountering some error messages: Error No.1 - Error NG8002: Cannot bind to 'ngModel' as it is not a recognized property of ...

Include type declarations for property values that resemble arrays in a generic object

Imagine you have a function that: receives an object with multiple properties and a property name; checks if the property holds an array; if it does, performs an action (such as printing the values it contains) Here's an illustration: function pro ...

The concept of HttpClient type safety appears to neglect the use of interfaces

TL;DR: A specific angular interface was linked to HttpClient.get() responses. The responses were transformed into a seemingly general object type. Even though attributes like id and title were not defined on the interface, they were still accessible in t ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

Changes made to an array in a called method using TypeScript do not appear in the calling function

The angular 6 calling-component-code I'm working with is as follows: this.appDowntimeService.getAllApplications(this.message, this.appDetails); Here's the service method being called: async getAllApplications(message: any[], appDetails: any[ ...

Provide a function or value as input and consistently output the value

I'm struggling to develop a function that accepts another function which, when called, should return a specific type of value. If the value itself is passed, it should just return that value. Unfortunately, I am facing difficulty in determining the f ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

Adding an object to an array in Postgres with TypeORM

I am currently facing an issue with the column in my Postgres database that has a data type of json. The code snippet for this scenario is as follows: @Column({ type: 'jsonb', nullable: false, default: [] }) us ...

Encountering an Angular 10 error: Trying to access a property that is undefined during test

In my journey to master Angular, I have taken on the challenge of building a clone of a todo-list application. Here are the interfaces and components that I have defined for this project: ListItem: import { Step } from './step'; export interf ...

Having trouble showing JSON data with Ionic 2 and Xcode?

Extracting JSON data from a JSON file in my project and viewing it using "ionic serve" on my Mac has been successful. However, I am facing an issue after building for IOS in XCode. I import the generated project into XCode as usual, but the JSON data is no ...

Typescript issue: The function 'forEach' is not applicable for type 'string'

Whenever I try to use the forEach() method, an error appears in my terminal. [ts] Property 'forEach' does not exist on type 'string'. Although my application functions properly in the browser, I want to eliminate these errors from the ...

Is the lack of WebStorm IDE support for Vue 3 Composition API a known issue or is there a problem with my configuration?

My experience with Vue 2 was smooth sailing, especially with the impressive WebStorm Plugin - it truly is top-notch and I believe it outperforms VS Code. However, as I delved into multiple Vue 3 projects using the Composition API, I encountered issues wit ...

The Node.js application successfully operates on a local environment, however encounters issues when attempting to run on docker resulting in an error message stating "sh

Despite successfully building the docker image, I am facing difficulties getting the container to run. Below is the content of the package.json file: { "name": "linked-versions-viewer", "version": "1.0.0", &quo ...

Angular interceptor automatically aborting API request

I have implemented a guard in my Angular application to validate user authorizations before granting access to a specific page. The guard makes an asynchronous API call to retrieve the necessary authorization information. While most of the time it works sm ...

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...