Problem encountered with the @ManyToOne and @OneToMany declarations

Hello there! I recently embarked on a new project utilizing TypeScript, TypeORM, and Postgres. Everything seemed to be going smoothly until I encountered some perplexing errors related to a relationship between @ManyToOne and @OneToMany. Below are my entity declarations along with the console error that I'm facing:

// Entity for products table
import  { Category } from './categories/categories.entity';
import { OrderDetails } from 'src/orders/details/orderDetails.entity';

import {
    Column,
    Entity,
    JoinTable,
    ManyToMany,
    ManyToOne,
    PrimaryGeneratedColumn,
} from 'typeorm';

@Entity({name: 'products`})

export class Product {   
 @PrimaryGeneratedColumn('uuid')

    id: string;

    @Column({ length: 50, nullable: false })
    name: string;

    @Column({ nullable: false })
    description: string;

    @Column('decimal', { precision: 10, scale: 2, nullable: false })
    price: number;

    @Column({ nullable: false })
    stock: number;

    @Column({ nullable: true, default: 'default_image_url' })
    imgUrl: string;

    @ManyToOne(() => Category, (category) => category.products)
    @JoinTable()
    category: Category;

    @ManyToMany(() => OrderDetails)
    @JoinTable()
    orderDetails: OrderDetails[];
}

// Purpose: Entity for categories table
import { Product } from '../products.entity';
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'categories' })
export class Category {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column({ length: 50, nullable: false })
    name: string;

    @OneToMany(() => Product, (product) => product.category)
    products: Product[];
}

Here is the specific error message I am encountering: src/categories/categories.entity.ts:22:4 - error TS2554: Expected 2-3 arguments, but got 1. 22 @OneToMany(() => Products) ~~~~~~~~~ node_modules/typeorm/decorator/relations/OneToMany.d.ts:8:102 8 export declare function OneToMany(typeFunctionOrTarget: string | ((type?: any) => ObjectType), inverseSide: string | ((object: T) => any), options?: RelationOptions): PropertyDecorator; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An argument for 'inverseSide' was not provided. ... [10:37:23] Found 4 errors. Watching for file changes.

I've double-checked my declarations and they appear to be correct. However, I'm at a loss as to why this error is occurring. It almost seems like an issue with TypeScript or Prettier. I even tried adding a second argument with an empty object {} or {cascade: true}, but unfortunately, it didn't resolve the problem.

Answer №1

Here are some tasks you can perform:

@Column({ nullable: false })
category_id: number;

@ManyToOne(() => Category, (category) => category.id, {
  nullable: false,
  onDelete: "CASCADE",
  onUpdate: "CASCADE",
})
@JoinColumn({
  name: "category_id",
  foreignKeyConstraintName: "category_fk",
})
category: Category;

@ManyToMany(() => OrderDetails)
@JoinTable({
  name: "order_rel",
  joinColumn: { name: "rel_id" },
  inverseJoinColumn: { name: "order_id" },
})
orderDetails: OrderDetails[];

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

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Is it feasible to have two interfaces in Typescript that reference each other?

I am facing an issue with two interfaces, UserProfile and Interest. Here is the code for both interfaces: export default interface UserProfile { userProfileId: string, rep: number, pfpUrl: string, bio: string, experience: "beginner" | " ...

Error message indicating a problem with global typings in Angular 2 when using Webpack is displayed

My project is utilizing angular 2 with webpack and during the setup process, I encountered Duplicate identifier errors when running the webpack watcher: ERROR in [default] /angular/typings/globals/node/index.d.ts:370:8 Duplicate identifier 'unescape& ...

Problems with updating HTML/Typescript in Visual Studio and Chrome are causing frustration

While working on my company's application locally and making HTML/TS changes, I am facing an issue. Whenever I save/hot reload and refresh the browser, no changes seem to take effect. I've tried stopping debugging, building/rebuilding, and runni ...

Angular Material's <mat-select> tag allows for the inclusion of an <input> element within it

I am attempting to place an input element inside the mat-select tag of the Angular Material element. However, I am facing an issue where I cannot input any text into the input field inside the select element. Below is the code I am using to search for elem ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

Encountered error E404 during installation of react packages using npm

Encountering an error while developing a Typescript-based fullstack project. The error message is as follows: npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@mui%2ficon-material - Not found npm ERR! 404 npm ERR! 404 '@mui ...

Breaking down an object using symbols as keys in Typescript

I'm encountering an error when running this code Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.: let symbol = Symbol() let obj = { [symbol] : 'value'} let { [symbol]: alias } = obj // ...

The relationship between Vue TypeScript props is influenced by the presence of another prop

Is there a way to define a property in <script setup lang="ts"> that depends on another property? For instance, how can I require a variable only if another variable is present? I attempted using defineProps<Props | PropsA>(), but e ...

The return type of a getter is `any` if the object contains a method and is processed by a generic function

I am facing an issue with my code where the getter's return type is set to any, even though the actual return type should be clear. There are certain additional functions triggering this behavior: // This is necessary for reproduction const wrapperFun ...

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

An error occurred while trying to set the property 'IS_CHECK' of an object that is undefined

I'm attempting to create a checkbox that, when selected, should also select everything else. I followed the code example provided in this tutorial for angular 2. However, I encountered an error: "ERROR TypeError: Cannot set property 'IS_CHECK&ap ...

Angular 13: Issue with Http Interceptor Not Completing Request

In my app, I have implemented a HtppInterceptor to manage a progress bar that starts and stops for most Http requests. However, I encountered an issue with certain api calls where the HttpHandler never finalizes, causing the progress bar to keep running in ...

The utilization of functions from a implemented interface results in the generation of a 'non-function' error

I recently created an interface that includes variables and a function. However, I encountered an issue when trying to utilize the implemented function for a specific class as it resulted in an 'ERROR TypeError: ...getPrice is not a function" Below ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Transforming a JavaScript component based on classes into a TypeScript component by employing dynamic prop destructuring

My current setup involves a class based component that looks like this class ArInput extends React.Component { render() { const { shadowless, success, error } = this.props; const inputStyles = [ styles.input, !shadowless && s ...

Retrieve contextual information within standard providers

I'm currently using nestjs to create a straightforward HTTP rest API, utilizing typeorm. I have set up 2 Postgres databases and would like the ability to access both, although not necessarily simultaneously. Essentially, I am looking to designate whi ...

Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as sh ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...