A one-to-many relationship does not include the insertion of the parent item

My database has a one to many relationship. When I perform a select operation, everything works correctly. However, when trying to insert data, the insertion occurs in the main table, but updates are triggered in other tables.

Error Log from Console

[0] query: BEGIN TRANSACTION

[0] query: INSERT INTO "tblCategory"("ID_CATEGORY", "NM_CATEGORY") VALUES (@0, @1)
-- PARAMETERS: [{"value":"BDA9A127-0851-4E2D-8FC7-52FBF27CFDF4","type":"uniqueidentifier","params":[]},{"value":Test,"type":"nvarchar","params":[]}]

[0] query: UPDATE "tblBook" SET "ID_CATEGORY" = @1 WHERE "ID_BOOK" = @0
-- PARAMETERS: ["F5465876-8003-44A6-BF97-9CBBE6D30C92",{"value":"BDA9A127-0851-4E2D-8FC7-52FBF27CFDF4","type":"uniqueidentifier","params":[]}]

[0] query: COMMIT

Expected Behavior

I expect the insert operation on tblCategory to work correctly. The problem lies with tblBook where an update is being triggered instead of an insert.

View Code

author.entity.ts

@Entity('tblCategory')
export class Category {
  @PrimaryColumn({ name: 'ID_CATEGORY', type: 'uniqueidentifier' })
  id: string;

  @Column({ name: 'NM_CATEGORY', type: 'nvarchar' })
  name: string;

  @OneToMany(type => Book, book => book.category)
  @JoinTable({
    name: 'tblBook',
    joinColumn: { name: 'ID_BOOK' },
    inverseJoinColumn: { name: 'ID_CATEGORY' },
  })
  books: Book[];

}

category.service.ts

@Injectable()
export class ForragemPastoService {
  constructor(
    @InjectRepository(Category)
    private readonly repository: Repository<Category>,
  ) {}

  async save(category: Category): Promise<Category> {
    await this.repository.save(category);
    const data = await this.repository.findOne(category.id, {
      relations: ['books'],
    });
    return data;
  }
}

book.entity.ts

@Entity('tblBook')
export class Book {
  @PrimaryColumn({ name: 'ID_BOOK', type: 'uniqueidentifier' })
  id: string;

  @Column({ name: 'DS_TITLE', type: 'nvarchar' })
  title: string;

  @Column({ name: 'DS_SUBTITILE', type: 'nvarchar' })
  subtitle: string;

  @ManyToOne(() => Category, m => m.books)
  @JoinColumn({ name: 'ID_CATEGORY' })
  category: Category;
}

Answer №1

Did you attempt setting up cascading? Giving it a try could be beneficial:

@OneToMany(type => Book, book => book.category, {cascade: true})

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

What is the best method for accessing a store in Next.js with Redux Toolkit?

Currently, I am working on incorporating integration testing for my application using Jest. To achieve this, I need to render components in order to interact with various queries. However, in order to render a component, it must be wrapped in a Provider to ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Dealing with User Registration and Form Data in MERN Stack: Challenges with FormData Usage and Verification

I've encountered an issue while working on a MERN stack application where I'm struggling to register a new user. The frontend form collects user data such as username, password, confirmPassword, salary, roles, and email, and sends it to the backe ...

Potential absence of object.ts(2531)

Currently, I am working on a project using Node.js with Typescript. My task involves finding a specific MongoDB document, updating certain values within it, and then saving the changes made. However, when I try to save the updated document, an error is bei ...

Results are only displayed upon submitting for the second time

Struggling with implementing a change password feature in Angular 7, On the backend side, if the current password is incorrect, it will return true. An error message should appear on the Angular side, but I'm encountering an issue where I have to cl ...

Testing the branch count of optional chaining in Typescript

I am struggling to grasp the concept of branch coverage, especially when it involves optional chaining in TypeScript. Below is my code snippet: type testingType = { b?: { a?: number }; }; export function example(input: testingType) { return input. ...

What is the process for list.map to handle waiting for a request response?

I'm facing an issue with my map function where it is not waiting for the request response before moving on to the next index. this.products = []; productList.map((product) => { this.productService.getProductInfo(product).subscribe(productData => ...

Adding an asterisk to mark a required field in Angular reactive form inputs is a simple task that can be accomplished with just a

Currently, I am in the process of developing an application that utilizes a reactive dynamic angular form. The fields for this form are retrieved from an API request and generated dynamically. I have encountered the need to include a 'required field& ...

Can TypeScript interfaces be used with various types?

Currently, I am receiving data from an endpoint that is providing a collection of different types all following the same interface. The structure looks something like this: interface CommonInterface { public type: string; public commonProperty1: i ...

The error message "Property 'pipe' is not found on 'ReadableStream<Uint8Array>'" indicates that the pipe method cannot be used on the given type

Within a function resembling Express.js in Next.js, I am working on fetching a CSV file with a URL that ends in .csv. Using the csv-parser library to stream the data without persisting the file and transform it into an array. Here is an excerpt of the code ...

Is there a way to conditionally redirect to a specific page using NextAuth?

My website has 2 points of user login: one is through my app and the other is via a link on a third-party site. If a user comes from the third-party site, they should be redirected back to it. The only method I can come up with to distinguish if a user is ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

What is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

Clicking the button fails to trigger the modal popup

Upon clicking a button, I am attempting to open a modal popup but encountering an error: The button click works, however, the popup does not appear after the event. test.only('Create Template', async({ page })=>{ await page.goto('h ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

Unable to modify the SVG color until it has been inserted into a canvas element

There is an SVG code that cannot be modified: <?xml version="1.0" encoding="UTF-8"?> <svg id="shape" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"> <path d="M29.57,19.75l-3. ...

Issue with the physical back button on Android devices

Whenever I press the physical Android Button I encounter the following error: While executing, an unhandled exception java.lang.IndexOutOfBoundsException: setSpan (2..2) goes beyond length 0 Here is my app.routing.ts import { LoginComponent } from " ...

What could be causing the excessive number of connections in my MongoDB instance?

This code snippet is crucial for my initial connection setup let cachedDbConnection: Db export async function establishDatabaseConnection(): Promise<{ db: Db }> { if (cachedDbConnection) { return { db: cachedDbConnection } } const client ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...

The problem with Typescript's RXJS `distinctUntilChanged` arises when the strictness of the parameter is set to undefined

The code snippet provided below is not functioning as expected: let source: Observable<{ key: number }> = of({ key: 123 }); source.pipe( distinctUntilChanged(undefined, v => v.key) ); Despite the existence of an alternative signature: export ...