What could be causing the undefined value in my Many-to-Many relationship field?

Currently, I am in the process of setting up a follower/following system. However, as I attempt to add a new user to the following list, I encounter an error stating

Cannot read property 'push' of undefined
. This issue results in the creation of two separate tables, one for users following others and one for users being followed by others. I am puzzled as to why the field is not being recognized. Any assistance on this matter would be greatly appreciated.

import { Length } from "class-validator";
import {
    Column,
    CreateDateColumn,
    Entity,
    JoinTable,
    ManyToMany,
    OneToMany,
    PrimaryColumn,
    RelationCount,
    Unique,
    UpdateDateColumn
} from "typeorm";

export class User {

    @PrimaryColumn()
    public user_id: string;

    @Column()
    public first_name: string;

    @Column()
    public last_name: string;

    @Column()
    public email: string;

    @Column()
    public phone_number: string;

    @Column()
    public username: string;

    @Column()
    @CreateDateColumn()
    public created_on: Date;

    @Column()
    @UpdateDateColumn()
    public updated_at: Date;

    @ManyToMany((type) => User, (user) => user.following)
    @JoinTable()
    public followers: User[];

    @ManyToMany((type) => User, (user) => user.followers)
    @JoinTable()
    public following: User[];

    @RelationCount((user: User) => user.followers)
    public followers_count: number;

    @RelationCount((user: User) => user.following)
    public following_count: number;
}

const { user_id, 
        follow_user_id } = req.
const user_repo = getRepository(User);
const user = await user_repo.findOne({
    where: {user_id}
});
const follow_user = new User();

follow_user.user_id = follow_user_id;
user.following.push(follow_user);
const result = user_repo.save(user);

The error revolves around this line:

user.following.push(follow_user);

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined

Answer №1

I recently faced a similar issue when working with OneToMany and ManyToOne relationships where the data returned null or was undefined.

To handle this issue, I came up with a solution by adding the following code snippet to the User class:

@AfterLoad()
async checkForNull() {
  if (!this.followers) {
    this.followers = []
  }

  if (!this.following) {
    this.following = []
  }
}

Check out the documentation

Answer №2

If you haven't tried the methods below, consider giving one of them a go.

1st method. Inside your User class.

    // Source code omission
    @ManyToMany((type) => User, (user) => user.followers)
    @JoinTable()
    public following: User[] = []; // ★ Added assignment
    // Source code omission

2nd method. Inside your User class.

export class User {
    // Source code omission
    constructor() { // ★ Added line
        this.following = []; // ★ Added line
    } // ★ Added line
}

3rd method. Wherever you are using the User class.

const follow_user = new User();

follow_user.user_id = follow_user_id;
user.following = []; // ★ Added line
user.following.push(follow_user);
const result = user_repo.save(user);

4th method. Wherever you are using the User class.

const follow_user = new User();

follow_user.user_id = follow_user_id;
user.following = [follow_user]; // ★ Edited line
const result = user_repo.save(user);

Answer №3

To prevent the occurrence of undefined lists, we employ this strategy:

@ManyToMany((type) => User, (user) => user.following)
@JoinTable()
private _followers: User[];

...

get followers() : User[] {
  if (!_followers) {
    _followers = [];
  }
  return _followers;
}

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

Middleware transformation pipeline implemented using Typescript types

In my quest to create a function that empowers middlewares (specifically Express ones) to enhance the Request object by adding properties to it, I aim for subsequent middlewares in the chain to utilize these additions while preserving data types. An examp ...

Example of Using Bluebird in a Chain of Catch and Then Functions

I am struggling to understand how promises work in my code flow setup. I want to create a register function with multiple steps, but I'm unsure of what is achievable and what is not. Imagine I have a register function where I need to: register a u ...

Steps for converting an Mqtt5 payload back into JSON

Is there a way to convert the result from Mqtt5Publish.getPayloadAsBytes() into a JSON string that is properly formatted? For example, how can I take a message published in this format: '{"SampleData0": "1.2.3", "SampleData1& ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

retrieve user input from various angular 6 components

Currently, I am in the process of developing a small web-based game using Angular 6. Within this project, I have two key components - play.component and setup.component. The main concept is to allow users to customize elements such as difficulty within the ...

What is the best way to set up an empty {[key: string]: string} object in TypeScript?

interface a { d: {[key: string]: string} } class a { d = {} } The error message returned is as follows: Subsequent property declarations must have the same type. Property 'd' must be of type '{ [key: string]: string; }', but ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...

What could be causing Next.js to re-render the entire page unnecessarily?

As a newcomer to Next.js, I am trying to develop an app where the header/navbar remains fixed at all times. Essentially, when the user navigates to different pages, only the main content should update without refreshing the navbar. Below is the code I have ...

Employing Class Categories in Static Procedures

I am currently working on developing a foundational Model that will serve as the base for a specific model class, which will have an interface detailing its attributes. Within the base Model class, I am aiming to incorporate a static factory() function th ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

"Unlocking the treasure trove: Extracting a single item from my Firebase real-time database using

Searching for the user's article in my Realtime database to display information. https://i.sstatic.net/yCdgf.png This is my Ionic script page Below are the imports I have: I am able to retrieve the user's ID, but I'm facing difficulty in ...

What is the process for defining a property type as a textual representation of a Type name in TypeScript?

Consider the following classes and interface: class Foo {} interface Bar {} I am looking to define a type that includes a property with a specified type: type DynamicPropertyName<T> = ... <-- ??? After defining the type, I want to use it like th ...

Leveraging multiple routes for a single component in Angular 6

Creating a component named Dashboard for admin requires passing the username in the route to find user information. This is the routing setup: {path:'dashboard/:username',component:DashboardComponent,children:[ {path:'role',component: ...

Guide to generating an array in JSON format within a dropdown menu option

Struggling to create a JSON array with select options instead of text fields? You're not alone. Spend hours trying to figure it out but still no luck? Take a look at this code snippet: function createJSON() { result = []; $("select[class=emai ...

Error encountered during the compilation of Angular2 Typescript due to difficulty in mapping a JSON response with underscores in the names

I recently started working with angular2 and I'm trying to map a JSON response to an array of custom objects. The issue I'm facing is that when I try to access a variable with an underscore in its name, I encounter a compile error. I followed the ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance: const func: Function = (@Decorator param: any) => { ... } or class SomeClass { public classProp: Function = (@Decorator param: any) => { ... } } Neither W ...

The data structure '{ variableName: string; }' cannot be directly assigned to a variable of type 'string'

When I see this error, it seems to make perfect sense based on what I am reading. However, the reason why I am getting it is still unclear to me. In the following example, myOtherVariable is a string and variableName should be too... Or at least that&apos ...