You must address the MustBeEntityError to proceed: Saving is not possible with the given value; it must be an entity, yet the value given is "undefined

I want to establish a one-to-one relationship between User and Profile. In this relationship, User is the owner, meaning that a user has a profile. However, when I execute the code, I encounter the following error message:

{ name: 'Greg', password: '123', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deb9acbbb99eb6bbacbbf0bdb1b3">[email protected]</a>' }
MustBeEntityError: Cannot save, given value must be an entity, instead "undefined" is given.

The issue arises because postman expects user.profile to be defined, but since I am developing a SPA with React on the frontend, the profile does not exist at the time of user signup. To address this problem, I consider setting a default value for the profile when calling the route to create the user. Later, I can create the profile separately and update it for the user using another route.

This is my implementation in User.ts:

@Entity("User")
export class User extends BaseEntity {
  @Column("number")
  @PrimaryGeneratedColumn()
  id: number;

  @Column("text")
  name: string;

  @Column("text")
  password: string;

  @Column("text")
  email: string;

  // https://stackoverflow.com/questions/62460079/typeorm-foreign-key-not-showing-on-a- 
  find-call
  @Column("number", { default: -1, name: "profileId" })
  profileId: number;

  @OneToOne(() => Profile, { cascade: true })
  @JoinColumn({ name: "profileId" })
  profile: Profile;

}

And here is my approach in Profile.ts:

@Entity("Profile")
export class Profile extends BaseEntity {
  @Column("number")
  @PrimaryGeneratedColumn()
  id: number;

  @Column("text", { nullable: true })
  gender: string;

  @Column("text", { nullable: true })
  occupation: string;

  @OneToOne(() => User, (user) => user.profile) // specify inverse side as a second parameter
  user: User;
}

Answer №1

In order to save data, you must first transform the object into an instance of the desired entity class for saving. Using Repository#create makes it simple to create an instance with initial values.

const userRepo = entityManager.getRepository(User);
await userRepo.save(
  userRepo.create({ name: 'Greg', password: '123', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f691849391b69e938493d895999b">[email protected]</a>' })
);

For more information, visit:

If you are not interested in the returned result, you can alternatively use Repository#insert.

await userRepo.insert({ name: 'Greg', password: '123', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9decbdcdef9d1dccbdc97dad6d4">[email protected]</a>' });

Answer №2

The handler requires a @Body() argument

@Post('/insert')
addNewEntry(@Body()newEntryDto:NewEntryDto):Promise<Entry>
{
    return this.entryService.addNewEntry(newEntryDto)
}

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

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

When attempting to create a generic key value interface, Typescript will throw an error if a mapped type is used that declares properties or methods

I am attempting to design an interface that can accept generic key-value pairs in the following format export interface GetModel<K extends string, T> { [key in K]: T; } However, I encountered this error message A mapped type may not declare prop ...

Having trouble launching the freshly developed Angular app

I'm encountering an issue with my newly created app - I can't seem to launch it. Error: The loader “C:/C#/Angular/my-app/src/app/app.component.css” is not providing a string as expected. https://i.sstatic.net/6Xjwd.png https://i.sstatic.ne ...

Transferring Information Across Angular Components via a Service Utilizing an RxJS Subject

The Goal I'm Pursuing In my Angular client app, I have two separate components. One component handles data fetching and processing from the server. My objective is to utilize the subscribe callback function to navigate to a different page where I can ...

Struggling with integrating Axios with Vue3

Can someone assist me in figuring out what is going wrong with my Axios and Vue3 implementation? The code I have makes an external call to retrieve the host IP Address of the machine it's running on... <template> <div id="app"> ...

Having trouble getting code hints to function properly with the official TypeScript plugin on Sublime Text 3

I am experiencing issues with getting code hinting to work using the official TypeScript plugin for Sublime Text 3 on Mac OSX 10.10.5 with Sublime 3. Despite installing it in the packages directory, I am unable to see any code hints. In accordance with th ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

The absence of a semicolon in the non-null assertion is causing an

Within my code, I have a function that arranges a set of cards according to a specific coordinate system: const orderCardsInPage = (items: OrderItemType[], pageCards: CardType[]) => { return pageCards.sort((firstCard, secondCard) => { con ...

What is the best way to categorize different types of countries in Typescript using optional keys?

I am working on creating a specialized country region map to ensure accurate selection of countries and their respective regions. I want to focus only on the relevant countries and regions, allowing for flexibility in choosing which keys to include while e ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Is it possible to create a data structure that enforces specific keys and values types during initialization?

When styling react components with MaterialUI's sx property, I've found that keeping the full style definition inline can lead to cluttered and overwhelming component bodies. To combat this, I've moved all the style definitions into a consta ...

Angular encountered an ERROR of type TypeError where it cannot access properties that are undefined when trying to read the 'title'

I designed a form and I am trying to save the information entered. However, when I attempt to use the save method, an error keeps popping up. How can I troubleshoot this issue and successfully save the data from the form? ...

Here is a unique rewrite: "Strategies for accessing interface-defined fields instead of mongoose schema-defined fields

Is there a way to modify my code to return "id" instead of "_id" and without "__v" to the client using express, mongoose, and TypeScript? Code snippet: Interface: export default interface Domain { name: string; objects: DomainObject[] } Creation Int ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

What could be causing the "undefined object" warning within this optional chain?

I encountered this issue: buyTicketData?.pricingOptions resulting in this error message: [tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx(280,25) TS2 ...

Guide on integrating a Web Worker included in an NPM module within a NextJS project

If you're experiencing issues, refer to the Github Repository here: https://github.com/kyledecot/next-worker-bug Within my NextJS application, there is an NPM package that I have bundled using webpack/ts-loader. This package includes a web Worker & W ...

Displaying data from an Angular subscription in a user interface form

I am attempting to transfer these item details to a form, but I keep encountering undefined values for this.itemDetails.item1Qty, etc. My goal is to display them in the Form UI. this.wareHouseGroup = this.formBuilder.group({ id: this.formBuilder.contr ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...