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

What could be the reason for my component not getting the asynchronous data?

Currently, I am delving into the intricacies of React and have been following a tutorial that covers creating components, passing props, setting state, and querying an API using useEffect(). Feeling confident in my understanding up to this point, I decided ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...

Css shaky letters transformation

[SOLUTION] To resolve this issue, you can utilize the will-change CSS property that enforces GPU rendering: will-change: transform; [ORIGINAL QUESTION] After extensive searching on the internet, I have yet to find a solution to a seemingly simple prob ...

Using the Presentational - Container (or Smart - Dumb) component approach in conjunction with Vuex

When it comes to managing the Presentational - Container (or Smart - Dumb) component pattern with Vuex, what is your recommended approach? Should the Presentational (or Dumb) components emit events to the parent or call Vuex actions? Imagine a scenario w ...

Discover the position of characters within a given string

I'm trying to accomplish a task similar to this: If the array [ "a", "b", "c" ] includes any of the characters in the constant word = "abracadabra", I want to retrieve that character along with its position in const word. My attempt so far looks lik ...

Switching the focus of detection from a child to a parent

I am currently working on enhancing the functionality of my UI to display selections dynamically as they are selected or de-selected. import { Wizard } from './report-common'; import { Router } from '@angular/router'; import { DataServ ...

Is there a way to run the mediapipe face detection codepen.io demo on my laptop?

After successfully running the mediapipe face detection demo from Mediapipe official website, I wanted to replicate it on my laptop. To achieve this, I created an 'index.html' file and meticulously transferred the code from the CodePen demo page ...

Encountering a problem with Chrome Extension localization upon installation - receiving an error message claiming default locale was not specified, despite having

Error Message: "The package has been deemed invalid due to the following reason: 'Localization was utilized, however default_locale was not specified in the manifest.' Issue: I have developed a customized extension and defined a default locale, ...

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...

Trigger on the cancellation or completion of a nested observable

I'm seeking a way to detect if an inner observable was not successfully completed (due to everyone unsubscribing) and then emit a value in that scenario. Something akin to defaultIfEmpty, but the current solution isn't effective. A trigger exis ...

Create a new instance of the parent class in TypeScript to achieve class inheritance

Looking for a solution to extending a base class Collection in JavaScript/TypeScript to handle domain-specific use cases by implementing a "destructing" method like filter that returns a new instance with filtered elements. In PHP, you can achieve this usi ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

What is the Typescript compiler utilized by Visual Studio 2015 when compiling on save?

Currently using Visual Studio 2015 Update 3 with TypeScript 2 for VS installed. I have a basic ASP.NET Core MVC web application with a few simple TypeScript files. The project contains a tsconfig.json file in the root folder with "compileOnSave": true. I ...

How to utilize the ternary operator efficiently to evaluate multiple conditions in React

Is there a way to change the style based on the route using react router? I want the description route to display in orange when the user is in the description route, white when in the teacher-add-course route, and green for all other routes. However, th ...

Comparison between referencing the DOM and storing references to the DOM elements

Can you explain the contrast between these two statements? $("#txt").val("123"); versus var txt=$("#txt"); txt.val("123"); Which statement is considered more effective in terms of efficiency? ...

Developing a React Native app using Expo and Firebase? Learn how to prevent Firebase details from

I have encountered a problem with my code while working on the user edit profile page in my react native app. The issue I am facing is related to displaying the previously inputted firebase details from the collection in the text input fields when the user ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...

WARNING: Alert raised due to the discovery of two offspring sharing identical keys, `${item}-${index}`

I have been facing the issue of receiving an error message 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and I am not sure what is causing it. Can someone please guide me on how to resolve this problem? Any help w ...

Enhancing performance with React.memo and TypeScript

I am currently developing a react native application. I am using the Item component within a flatlist to display data, however, I encountered an error in the editor regarding the second parameter of React.memo: The error message reads: 'Type 'bo ...

Using JS and d3.js to eliminate or combine duplicate connections in a d3.js node diagram

Hey there! Hello, I am new to working with js/d3.js and tackling a small project. Here are some of my previous inquiries: D3.js: Dynamically create source and target based on identical JSON values JS / d3.js: Steps for highlighting adjacent links My cu ...