Unable to insert into a many-to-many table because of a restriction with the foreign key

I am encountering an issue with my schedule table, which is derived from a many-to-many relationship between a classes and users table.

User typeorm schema

@ManyToMany(type => UClass, c => c.users, {cascade: true, onDelete: "CASCADE"})
    @JoinTable({name: "schedule"})
    classes: UClass[]

Class typeorm schema

 @ManyToMany(type => User, u => u.classes)
    @JoinTable({name: "schedule"})
    users: User[]

When attempting to create a user:

{
    "username":"a",
    ...(rest of data)
    "classes":[{"id":"f602a286-3df1-4912-9165-2375b5e45bdd"}]
}

An error is triggered displaying:

QueryFailedError: insert or update on table \"schedule\" violates foreign key constraint \"FK_d796103491cf0bae197dda59477\

I am uncertain why this foreign key error is occurring since both the provided user and class ids are valid. Any assistance would be greatly appreciated.

Answer №1

After spending almost a full day troubleshooting, it dawned on me that the register function was actually working fine in my production app. I decided to trace back my steps using GitHub to see what changes I had made since updating the production version. It turns out that nesting repositories within another repository caused the database migration to behave differently. The solution was simple: I just needed to modify

userRepository: Repository<User>;
classRepository: Repository<UClass>;
scheduleRepository: Repository<any>;

    constructor() {
        this.userRepository = getManager().getRepository(User);
        this.classRepository = getManager().getRepository(UClass);
    }

to

userRepository: Repository<User>;
scheduleRepository: Repository<any>;

    constructor() {
        this.userRepository = getManager().getRepository(User);
    }

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

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

Adding a click functionality to a dynamically generated anchor tag in angular.js

Recently, I encountered a requirement that involved converting a part of plain text into a clickable link and then adding a click handler to it. The goal was to display some details in a popup when the link is clicked. In order to convert the normal strin ...

Is it possible to define a class prior to exporting it in typescript/angular? | TSLint warning: unused expression, assignment or function call expected

Coming from the realm of React, I am well-versed in the fundamental concepts of launching an application with an index.js, avoiding direct involvement with HTML, and utilizing import and export statements to share views among different JavaScript files. In ...

Having trouble retrieving the data returned from the service in an angular component

Having trouble retrieving data from a service in an Angular component. Here is the service code: getData(fromDate: string, toDate: string): Observable<WfAverageTime[]> { const url ="http://testApi/getData" return this.http.get< ...

The property name in VS Code features a star symbol (★) as part of its design

Lately, I've observed that certain objects in VS Code written in JavaScript\TypeScript have properties marked with an asterisk. What could this indicate? For instance: I created a string array named 'myArray' https://i.sstatic.net/vco2 ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Labeling src library files with namespaces

I have developed a ReactJS website that interacts with a library called analyzejs which was created in another programming language. While I am able to call functions from this library, I do not have much flexibility to modify its contents. Up until now, ...

What is the process of 'initializing' an object in TypeScript?

Is it possible that retrieving a json from a mongodb database and casting it does not trigger the typescript constructor? What could be causing this issue? I have a Team class export class Team { transformations: { [transformationId: string]: Transfor ...

Jest is unable to handle ESM local imports during resolution

I am encountering an issue with my Typescript project that contains two files, a.ts and b.ts. In a.ts, I have imported b.ts using the following syntax: import * from "./b.js" While this setup works smoothly with Typescript, Jest (using ts-jest) ...

"Successful deletion with Express, yet error message of 'Not Found' displayed

I've implemented this boilerplate to build my API, utilizing express and typeorm with typescript. When attempting to delete a question, the deletion process works smoothly but I receive a 404 not found response. Below is my Question.ts class: @Entit ...

The typed union type FormGroup in Angular stands out for its versatility and robustness

Within my application, users select a value from a dropdown menu to determine which type of FormGroup should be utilized. These formGroups serve as "additional information" based on the selection made. I am currently working with three distinct types of f ...

How can I transform a string array into an object array using Angular 2?

If I have an array like this: categories = ['Fruit', 'Vegetable', 'Grain']; I want to transform it into an array of objects with the following structure: [ { id: 1, type: 'Fruit' }, { ...

Receiving error in TypeScript while using the 'required' attribute in the input field: "Cannot assign type 'string | undefined' to parameter expecting type 'string'"

In my TypeScript code, I am currently in the process of transitioning from utilizing useState to useRef for capturing text input values. This change is recommended when no additional manipulation necessitating state or rerenders is required. While I have ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Is it advisable to incorporate 'use server' into every function that retrieves confidential information within server components in Next.js?

By default, server components are enabled in Next.js 13. I'm contemplating whether I should wrap each fetch call in a separate function and include 'use server' to conceal the function's code or if it's acceptable to directly use f ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

I'm having trouble resolving this error that keeps popping up on this particular line of code: "registrationForm : FormGroup;" Can anyone help me troubleshoot this

***Issue: src/app/r-form-example/r-form-example.component.ts:11:3 - error TS2564: Property 'registrationForm' lacks an initializer and is not definitely set in the constructor. An error has been detected in the code snippet above. import { Comp ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Can you provide details about the launch configuration for pwa-node in VSCode?

When setting up npm debugging in VSCode, I couldn't help but notice that the default launch configuration is labeled as "pwa-node" instead of just "node". Here's what the "Launch via NPM" configuration looks like: https://i.sstatic.net/EQ5c5.pn ...