"An issue encountered with TypeORM repository where values are not being set

My custom entity is defined below:

@Entity()
export class Game extends BaseEntity {

     @PrimaryGeneratedColumn({
        name: "id",
     })
     private _id: number;

     @Column({
        name: "name",
        type: "varchar",
        nullable: false,
     })
     private _name: string;


    get id(): number {
        return this._id;
    }

    set id(id: number) {
        this._id = id;
    }

    get name(): string {
        return this._name;
    }

    set name(name: string) {
        this._name = name;
    }
}

When creating a new instance of Game, the Repository API is utilized.

The process involves:

import { getRepository } from "typeorm";
import { Game } from "../entities/game.entity";
import { InsertGameConfig } from "../interfaces/entities/game";

public async insert(config: InsertGameConfig) {
    return await getRepository(Game).create(config).save();
}

This function can be called as follows:

await insert({
  name: "test",
});

However, looking at the MySQL query log reveals:

INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, DEFAULT)

In contrast, manually setting each value like this:

const game = new Game();
game.name = config.name;
return await game.save();

Results in the correct SQL query:

INSERT INTO `game`(`id`, `name`) VALUES (DEFAULT, "test")

According to TypeOrm documentation:

create - Creates a new instance based on the provided properties.

const user = repository.create(); // same as const user = new User();
const user = repository.create({
    id: 1,
    firstName: "Timber",
    lastName: "Saw"
}); // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";

Note

Setting the attributes of the class to public allows create to work correctly. However, using private attributes with getters/setters causes issues.

Answer №1

It's unusual to find an ORM that utilizes object private fields as data fields, regardless of the programming language. Private fields are not accessible from outside a specific class instance, so it wouldn't make sense for the ORM to interact with them using decorators or attributes. Even if the ORM could access private properties, determining which getter/setter corresponds to a property like _name would be ambiguous.

The best practice, as outlined in the documentation, is to define classes with public properties only:

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;
}

Currently, this approach appears to be the most appropriate method to use with ORMs.

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

An error in PHP has been detected within the CodeIgniter framework

I have encountered an error that has been frustrating me lately: An unexpected PHP Error occurred with the following details: Severity: Warning Message: strip_tags() expects parameter 1 to be string, array given Filename: inscription/loginform3.php Line ...

The page has been updated following a refresh

I'm currently working on developing an Instagram-inspired platform using Angular 6, but I've run into a puzzling issue. When I refresh the page in my home component, everything reloads correctly and displays all my posts as expected. However, if ...

I have to choose the top five and bottom five numbers from a set of 60 numbers

In a list of 60 numbers, I am looking to identify both the top five and bottom five based on their count. Using the table "scores," here is the query to select the top five: SELECT * FROM scores ORDER BY count DESC LIMIT 5 This query will give you the t ...

Error message: Material Design UI - The type 'string' cannot be assigned to the type Icon

I am currently working on a component that is responsible for returning the specific icon based on the prop that is passed. Here is a simplified version of how it works in my application: import * as icons from "@mui/icons-material"; interface I ...

Displaying a child component as a standalone page rather than integrating it within the parent component's body

I'm currently working on implementing nested navigation in my website, but I am facing challenges with loading the child component without the need to include a router-outlet in the parent component. This setup is causing the child component's co ...

The value returned by UseSelector is not defined

this code snippet is responsible for monitoring the state of a shopping cart that contains various bets placed by the user const { games } = useSelector((state: any) => state.cart) which is then passed to another component like this <AppRecentUserG ...

Nestjs Roles Decorator: Unusual behavior in extracting user from payload information

I have been working on implementing my Roles Decorator in Nestjs and it has been going well. However, I encountered an issue when trying to compare the user data from the jwt-token payload to the required role. Strangely, I found that I can only access the ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Encountering challenges with Object-Oriented Programming combined with Typescript: Are you experiencing a

Currently, I'm in the process of building a comprehensive authentication application using the MERN stack entirely in TypeScript. However, I am encountering some issues (specifically type errors) with my userController file. Here is my routes file: i ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

Frequent occurrence when a variable is utilized prior to being assigned

I am currently working with a module import pino, { Logger } from 'pino'; let logger: Logger; if (process.env.NODE_ENV === 'production') { const dest = pino.extreme(); logger = pino(dest); } if (process.env.NODE_ENV === &apo ...

When the input field is not selected, switch it to display as plain text

I have a table where the cells become editable when clicked on by a user. I want the editable area to revert back to plain text with the updated value once the user deselects the text field. Is it possible to utilize AJAX to update a database with the new ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Leverage Prisma's auto-generated types as the input type for functions

Exploring the capabilities of Prisma ORM has led me to experiment with creating models and generating the PrismaClient. Initially, I thought it would be possible to utilize the generated types for variables and response types, but that doesn't seem to ...

methods for transforming a string into an object

let styleValues = "{ "background-color": "#4a90e2", "padding": 10px }"; JSON.parse(styleValues); The code snippet above triggers the error below: Uncaught SyntaxError: Unexpected token p in JSON at position 46 ...

Detecting changes in custom ExceptionHandler may cause delays in recognition

Currently, I am working on integrating a personalized ExceptionHandler in an Angular 2 application that sends unhandled errors to a customized AlertsService. The objective is to enable the main App component to subscribe to the alerts provided by the Alert ...

Updating a data structure to include a new attribute within a subcategory (Routes)

Is there a way to include the whenRoute optional parameter in the data section of the Route type without directly altering the Angular types file? const routes: Routes = [ { path: 'pages', loadChildren: () => import('./pages/pa ...

React Typescript: Turn off spellchecking

Struggling to turn off spell check for typescript <form> <input type='text' name='accountName' ref={accountName} onChange={checkName} spellCheck='false' // <====== Disable spellche ...

Ways to access the parent value within a child component in Angular 4

I am a beginner in angular4 Currently, I am working on a Registration process that involves multiple steps. To control the visibility of these steps based on certain conditions, I am using the hide/show functionality. The Registration process consists of ...

Exploring Typescript: A guide to iterating through a Nodelist of HTML elements and retrieving their values

I'm struggling to retrieve values from a Nodelist of input elements. Can anyone help me out? let subtitleElements = document.querySelectorAll( '.add-article__form-subtitle' ); ...