TypeORM Error: Trying to access the 'id' property of an undefined object

I attempted to implement migration in TypeORM as shown below:

TableExample.entity.ts

@Entity({ name: 'table_example' })
export class TableExampleEntity {

    constructor(properties : TableExampleInterface) {
        this.id = properties.id;
    }

    @PrimaryColumn({
        name: 'id',
        type: 'uuid',
        generated: 'uuid',
        default: 'uuid_generate_v4()',
    })
    id? : string;

}

TableExample.interface.ts

export interface TableExampleInterface{
    id? : string;
}

and migration file

import {MigrationInterface, QueryRunner, Table} from 'typeorm';

export class createSongEntities1591077091789 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(new Table({
            name: 'table_example',
            columns: [
                {
                    name: 'id',
                    type: 'uuid',
                    generationStrategy: 'uuid',
                    default: 'uuid_generate_v4()',
                    isPrimary: true,
                },
            ],
        }));
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.dropTable('table_example');
    }

}

Upon running the migration, the node server threw the following error Stack trace

Error during migration run:
TypeError: Cannot read property 'id' of undefined
    at new TableExampleEntity (...\src\entities\TableExample.entity.ts:17:34)
    at EntityMetadata.create (...\src\metadata\EntityMetadata.ts:524:19)
    at EntityMetadataValidator.validate (...\src\metadata-builder\EntityMetadataValidator.ts:112:47)  
    at ...\src\metadata-builder\EntityMetadataValidator.ts:45:56
    at Array.forEach (<anonymous>)
    at EntityMetadataValidator.validateMany (...\src\metadata-builder\EntityMetadataValidator.ts:45:25)
    ...

What could be the issue here? Any assistance would be greatly appreciated!

Answer №1

According to the typeorm documentation, you can find more information here:

The entity constructor's arguments should be optional when using typeorm. This is because the ORM creates instances of entity classes when retrieving data from the database, and it may not know about your constructor arguments.

In your situation, typeorm creates an instance of the entity without passing any arguments to the constructor. As a result, the properties parameter remains undefined.

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

Refreshing the Mat Dialog content when removing items in Angular Material

I have successfully implemented a mat dialog table with 3 columns - name, email, and delete icon. When the user clicks on the delete icon, it prompts a confirmation message to confirm the deletion. Upon confirming, the item is removed from the database. Ho ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

Issue encountered when trying to integrate Angular2 with Visual Studio 2015 Update

Starting my journey with Angular2 in Visual Studio 2015. Following advice from this helpful article. Encountering an issue when running the index.html file, it gets stuck on 'Loading...'. Here are the key configurations and code files being use ...

Trouble with storing data in Angular Reactive Form

During my work on a project involving reactive forms, I encountered an issue with form submission. I had implemented a 'Submit' button that should submit the form upon clicking. Additionally, there was an anchor tag that, when clicked, added new ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

Discovering the specific value within an array of various objects through Angular

Within a list of objects, I am specifically looking to extract the name "sample 4" from the second set of objects with an ID of 2. How can this value be retrieved using JavaScript or Angular? {Id: 1, name: sample 1, code: "type", order: 1} {Id: 1, name: ...

Tips for resolving Circular dependency issue in node.js?

While working on a post request, I encountered an issue with the code below: try{ const _id = await db.collection('UserInformation').insertOne(userObj); await db.collection('LoggedInUser').updateOne({ userId: _id }, { '$set&ap ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

Inversify is a proven method for effectively injecting dependencies into a multitude of domain classes

Struggling to navigate dependencies and injections in a TypeScript-built rest web service without relying heavily on inversify for my domain classes, in line with the dependency inversion principle. Here's an overview of the project structure: core/ ...

Limit file upload size to less than 1MB in Angular 2 with typescript using ng2-file-upload

Having issue with my code - I can't upload a file larger than 1mb even though maxFileSize is set to 50mb. Can anyone help me troubleshoot? @Component({ moduleId: module.id, selector: 'NeedAnalysisConsult', templateUrl: 'nee ...

Is it possible to define an interface to inherit keys from another interface?

I have two different interfaces that I need to align their key structure, but not necessarily the values they hold. One interface (Thing) is sourced from an external library, while the other interface (ThingOptions) is defined in my own project. interface ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Having difficulty sending the [ctrl][p] keys to a page that is not using Angular framework

Working with protractor version 5.1.2, Angular 5, and typescript 2.4.2 When attempting to trigger a 'print' function using the shortcut keys '[ctrl][p]' in protractor on a non-angular page, I encountered an issue. Within my protractor ...

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

The circular reference error in Typescript occurs when a class extends a value that is either undefined, not a constructor,

Let me begin by sharing some context: I am currently employed at a company where I have taken over the codebase. To better understand the issue, I decided to replicate it in a new nestjs project, which involves 4 entities (for demonstration purposes only). ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Merging Two JSON Objects into a Single Object Using Angular 4-6

Two JSONs are available: The first one (with a length of 200): {date_end: "2099-12-31", id: "2341"} {date_end: "2099-12-31" id: "2342"} ... The second one (length 200): {type: "free", discount:"none", warranty: "yes"} {type: "free", discount:"none", ...