What could be causing NestJS/TypeORM to remove the attribute passed in during save operation?

Embarking on my Nest JS journey, I set up my first project to familiarize myself with it. Despite successfully working with the Organization entity, I encountered a roadblock when trying to create a User - organizationId IS NULL and cannot be saved.

Here are my entities:

import { User } from "src/modules/user/entities/user.entity";
import { IOrganization } from "../interfaces/organization.interface";
import { Column, CreateDateColumn, Entity, PrimaryColumn, UpdateDateColumn, OneToMany } from "typeorm";

@Entity()
export class Organization implements IOrganization {
  @PrimaryColumn()
  id: string

  @Column({ nullable: false })
  name: string

  @OneToMany(() => User, (user) => user.organization)
  users: User[]

  @CreateDateColumn()
  createdAt: Date

  @UpdateDateColumn()
  updatedAt: Date
}
import { Organization } from "src/modules/organization/entities/organization.entity";
import { Column, CreateDateColumn, Entity, PrimaryColumn, UpdateDateColumn, ManyToOne, JoinColumn } from "typeorm";
import { Role } from "../enums/user.enum";

@Entity()
export class User {
  @PrimaryColumn()
  id: string

  @ManyToOne(() => Organization, (organization) => organization.users, {
    nullable: false,
  })
  @JoinColumn({ name: "organizationId" })
  organization: Organization

  @Column({ unique: true, nullable: false })
  email: string
  
  @Column ({
    type: "enum",
    enum: Role,
    default: Role.USER,
    nullable: false,
  })
  role: Role

  @Column({ nullable: false })
  name: string

  @CreateDateColumn()
  createdAt: Date

  @UpdateDateColumn()
  updatedAt: Date
}

Moving on to my User Module:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './entities/user.entity';
import { OrganizationService } from '../organization/organization.service';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

Followed by my User Controller:

import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Roles } from 'src/decorators/roles.decorator';
import { AuthGuard } from '@nestjs/passport';
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

// Rest of the controller methods...
}

And wrapping it up with my User Service:

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { IUser } from './interfaces/user.interface';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

// Rest of the service methods...
}

The issue arises during creation where the organizationId ends up as NULL in the database, triggering a violation of the not-null constraint. I am unsure why the data passed does not include organizationId. Seeking assistance for this seemingly simple problem, I attempted various solutions like importing the organization modules and modifying the repository import, but to no avail.

Answer №1

 @ManyToOne(() => Organization, (organization) => organization.users, {
    nullable: false,
  })
  @JoinColumn({ name: "organizationId" })
  organization: Organization

In this scenario, the 'organization' is considered an entity and TypeORM requires you to insert the complete data rather than just the ID. To achieve this, you can use the following approach:

 async create(createUserDto: CreateUserDto): Promise<IUser> {
    console.log('Created User DTO: ', createUserDto);
    const create = this.userRepository.create(createUserDto);
    return await this.userRepository.save(create);
  }

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

Incorporate Subtitles into Your Website Using JWPlayer

I want to incorporate Video Captions similar to those seen on Lynda.com, for example at The captions should synchronize with the player and also appear in a separate block of HTML below the player. I am using JWPlayer for my video and have successfully in ...

The React Query devtools are failing to display

I am currently working on a project using React Query, but for some reason, the DevTools icon is not appearing on my screen. I have checked the console for errors, but there are none. I am following a tutorial on YouTube to help me with this. Here is a sn ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

jQuery functionality restricted to desktop devices

I am attempting to disable a jQuery function specifically for mobile devices. I found some instructions that seem helpful on this page. Unfortunately, following the instructions did not work for me. Here is the code snippet I have: var isMobile = /Androi ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Calculate the total sum of selected values in a multiple select dropdown using jQuery

Is there a way to calculate the sum of selected items in a multiple selection dropdown menu? For instance, if I select "X12SO" and "X13SO", their values should add up to 30. let total = 0; $("select[name='myselect[]'] option").each(function(){ ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

The functionality of the Bootstrap dropdown list button is not functioning properly on mobile devices

Currently, I am in the process of developing a website and testing its mobile view on my iPhone. The website is still using bootstrap 3, but I have encountered some issues. When I tap on the navigation button on my iPhone, nothing happens - no dropdown lis ...

Customizing the Material UI v5 theme with Typescript is impossible

I'm attempting to customize the color scheme of my theme, but I am encountering issues with accessing the colors from the palette using theme.palette. Here is a snippet of my theme section: import { createTheme } from "@mui/material/styles&qu ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

What separates the act of declaring a generic function from explicitly declaring a type for that very same generic function?

Here are two instances demonstrating the use of a generic function: function myGenericFunction<TFunc extends Function>(target:TFunc): string { return target.toString(); } Based on this response, this represents a declaration for a generic funct ...

Is there a way to add 100 headings to a webpage without using a loop when the page loads

Just joining this platform, so please be patient with me! The task at hand is to insert 100 h3 headings on page load ("Accusation 1, Accusation 2, Accusation 3,...Accusation 100"). We are restricted to using only 1 loop throughout the lab, which will also ...

Automatically update button appearance upon reaching zero value using JavaScript

Whenever I click the button, the user's HP decreases until it reaches 0 and then the button changes. However, a peculiar issue arises when the userHealth hits zero - the button does not change immediately. An additional click is required for the butto ...

Manage Blob data using Ajax request in spring MVC

My current project involves working with Blob data in spring MVC using jquery Ajax calls. Specifically, I am developing a banking application where I need to send an ajax request to retrieve all client details. However, the issue lies in dealing with the ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...