Unable to remove a OneToMany entry in TypeORM

I am currently working with the following database schemas:

@Entity()
export class Question extends BaseEntity {
  @PrimaryColumn()
  messageId: string;

  @Column()
  authorId: string;

  @Column()
  question: string;

  @Column("varchar", { array: true })
  possibleAnswers: string[];

  @Column()
  isAnonymous: boolean;

  @OneToMany(() => Answer, (answer) => answer.question, { eager: true })
  answers: Answer[];

  get formattedAnswers() {
    return this.possibleAnswers
      .map((answer, idx) => `${numericEmojis[idx]}: **${answer}**`)
      .join("\n");
  }
}

@Entity()
@Unique("uc_ids", ["userId", "questionMessageId"])
export class Answer extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  userId: string;

  @Column()
  answerIndex: number;

  @ManyToOne(() => Question, (question) => question.answers)
  question: Question;

  @Column({ readonly: true })
  // @ts-expect-error
  private readonly questionMessageId: string;
}

When attempting to delete a question like this:

const question = await Question.findOne(message.id);

await Question.delete(question);

An error is triggered:

err: query: SELECT "Question"."message_id" AS "Question_message_id", "Question"."author_id" AS "Question_author_id", "Question"."question" AS "Question_question", "Question"."possible_answers" AS "Question_possible_answers", "Question"."is_anonymous" AS "Question_is_anonymous", "Question__answers"."id" AS "Question__answers_id", "Question__answers"."user_id" AS "Question__answers_user_id", "Question__answers"."answer_index" AS "Question__answers_answer_index", "Question__answers"."question_message_id" AS "Question__answers_question_message_id" FROM "question" "Question" LEFT JOIN "answer" "Question__answers" ON "Question__answers"."question_message_id"="Question"."message_id" WHERE "Question"."message_id" IN ($1) -- PARAMETERS: ["729340583583285289"]
err: (node:19515) UnhandledPromiseRejectionWarning: EntityColumnNotFound: No entity column "answers" was found.

I originally intended to implement a cascade delete functionality, but even after removing it, the error persists. How can I rectify this issue? My database is Postgres and I am using the SnakeNamingStrategy.

Answer №1

Adding onDelete:"CASCADE" or onDelete:"SET NULL" works perfectly for me.

These are the schemas I am currently using:

@Entity()
export class Question extends BaseEntity {
  @PrimaryColumn()
  messageId: string;

  @Column()
  authorId: string;

  @Column()
  question: string;

  @Column("varchar", { array: true })
  possibleAnswers: string[];

  @Column()
  isAnonymous: boolean;

  @OneToMany(() => Answer, (answer) => answer.question, { eager: true })
  answers: Answer[];

  get formattedAnswers() {
    return this.possibleAnswers
      .map((answer, idx) => `${numericEmojis[idx]}: **${answer}**`)
      .join("\n");
  }
}

@Entity()
@Unique("uc_ids", ["userId", "questionMessageId"])
export class Answer extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  userId: string;

  @Column()
  answerIndex: number;
  
  // Setting onDelete as cascade for automatic deletion from parent entity
  @ManyToOne(() => Question, (question) => question.answers, { cascade: true, onDelete: "CASCADE" })
  question: Question;

  @Column({ readonly: true })
  // @ts-expect-error
  private readonly questionMessageId: string;
}

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

Unlock Buffer - JavaScript

I'm working with a simple JavaScript code snippet. let str = "Hello World"; console.log(Buffer.from(str,"utf-8")); The output is: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64> Is there a way to extract the bytes from the Buffe ...

Exploring the Power of PrimeNG and Observables in Angular 4 with RxJS

After configuring my Angular 4 project with a service like this: const usersURL = 'http://my.super.url.php'; @Injectable() export class UserService { users: Observable<User[]> constructor (public http:Http) let tick$ = Observ ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

Receiving an error in TypeScript stating that the property or data does not exist on the type for Vue props

I've recently integrated TypeScript into my Vue project, and now I'm encountering an error every time I try to access a value in props or data: 37:46 Property 'activity' does not exist on type '{ props: { activity: { type: ObjectC ...

Guide on efficiently injecting data into a database using JavaScript and SQL from an array of objects

Let's simplify this process. I am creating a dynamic form for clients to submit data to a PostgreSQL database using React on the front end and NodeJs on the back end. Once the form is filled out, the inputs are stored in an array of objects like this ...

NestJS Ensures Type Safety for Mongoose Models, but Model Functions Expecting Incorrect Types (Any)

Shema Interfaces export interface MyCat { name: string; color: string; } export type Cat = MyCat & Document; export const CatSchema = new Schema({ name: { type: String, required: true, }, color: { type: String, required: tr ...

Keep verifying the boolean value repeatedly

I've been working on implementing infinite scroll functionality for my card elements. Within my data.service file, I have a variable called reload that is utilized to determine whether more data needs to be loaded. This variable is set to true when th ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

Is there a way to incorporate a dropdown feature into a search bar using Ant Design?

I'm currently working on a project that requires me to incorporate two drop-down menus inside the search box. Despite following the guidelines provided in the documentation (https://ant.design/components/input), I encountered a problem when trying to ...

I'm trying to figure out how to access the array field of an object in TypeScript. It seems like the type 'unknown' is required to have a '[Symbol.iterator]()' method that returns an iterator

I'm currently tackling an issue with my helper function that updates a form field based on the fieldname. For example, if it's the name field, then form.name will be updated. If it's user[0].name, then the name at index 0 of form.users will ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Locating the source and reason behind the [object ErrorEvent] being triggered

I'm facing an issue where one of my tests is failing and the log is not providing any useful information, apart from indicating which test failed... LoginComponent should display username & password error message and not call login when passed no ...

Experimenting with Typescript, conducting API call tests within Redux actions, mimicking classes with Enzyme, and using Jest

I am facing an issue where I need to mock a class called Api that is utilized within my redux actions. This class is responsible for making axios get and post requests which also need to be mocked. Despite following tutorials on how to mock axios and class ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Only object types can be used to create rest types. Error: ts(2700)

As I work on developing a custom input component for my project, I am encountering an issue unlike the smooth creation of the custom button component: Button Component (smooth operation) export type ButtonProps = { color: 'default' | 'pr ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...

Ensure that the background view remains interactive while adding an overlay on top for an enhanced user experience

Hey everyone, I could use some help with a question I have. My issue is that I am struggling to figure out how to make two views overlap while still allowing the background view to be interactive. Currently, I am using absolute positioning for the foregr ...