question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Exclude() at entity is also exclude data at inserting to database

See original GitHub issue

Hello. I’m Happy to using CRUD.

I have some question about using Exclude().

The wiki tells us to use Exclude() to exclude the value when returning the entity’s value to the user.

However, if Exclude() is Annotated on an entity column, the data is excluded during the process of inserting data and marked as DEFAULT at TypeOrm Logging. Therefore, an error occurs on a column without a DEFAULT value.

Is this intended? Is it a bug?

I can replace it using the DTO and Serialize options, but I think you should be able to use the usage from the wiki as well.

My understanding is Annotated Exclude() is hide data to User when serialized. and not banning data when inserting. Is it correct?

Entity

import { Column, Entity } from "typeorm";
import { Exclude } from 'class-transformer';

@Entity("flag", { schema: "crypto" })
export class Flag {
  // ...
  @Exclude()
  @Column("int", { primary: true, name: "id" })
  id: number;

  @Column("int", { name: "idn", nullable: true })
  idn: number | null;
  // ...
}

DTO

export class FlagDto {
   // ...
    @IsNumber()
    id: number;
    idn: number;
  //...
}

Controller

@Crud({
    model: {
        type: Flag
    },
    dto: {
        create: FlagDto
    }
})
@UseGuards(AuthGuard)
@Controller('flags')

request body*

{
    "id": 15,
    "idn": 159123,
    "defaultUse": 1,
    "apiUse": 0,
    "officeUse": 0
}

typeorm log

query: START TRANSACTION
query: INSERT INTO `flag`(`id`, `idn`, `default_use`, `default_use_change_at`, `api_use`, `api_use_change_at`, `office_use`, `office_use_change_at`, `updated_at`, `created_at`)
VALUES (DEFAULT, ?, ?, DEFAULT, ?, DEFAULT, ?, DEFAULT, DEFAULT, DEFAULT)
-- PARAMETERS: [159123,1,0,0]
query failed: INSERT INTO `flag`(`id`, `idn`, `default_use`, `default_use_change_at`, `api_use`, `api_use_change_at`, `office_use`, `office_use_change_at`, `updated_at`, `created_at`)
VALUES (DEFAULT, ?, ?, DEFAULT, ?, DEFAULT, ?, DEFAULT, DEFAULT, DEFAULT)
-- PARAMETERS: [159123,1,0,0]
error: Error: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
yura-lovecommented, Apr 19, 2020

solution for this issue without “serialize option” is this.

import {Exclude} from "class-transformer";

export class User {

    id: number;

    email: string;

    @Exclude({ toPlainOnly: true })
    password: string;
}

when CRUD serlizing entity, it excluded by class-transformer only when entity is responsed,

1reaction
yura-lovecommented, Apr 27, 2020

Hello, I have same issue here.I know serialize may be a useful method. but in my project, there is some addtional route, like that:

@Crud({
  model: {
    type: Admin,
  },
  query: {
    exclude: ['pwd'] // is only works for crud route
  },
})
@Controller('admin')
export class AdminController {
  constructor(public service: AdminService) {}

  get base(): CrudController<Admin> {
    return this
  }

  @Post('login')
  @ValidatePipe()
  login(@Body() loginDto: LoginDto) {
    return this.service.login(loginDto)
  }
}

I want add /login route, if success, return this admin and a token

I want to exclude the pwd either, so I add @exclude() at the entity

part of my entity:

{
  ...

  @Exclude()
  @IsOptional({ groups: [UPDATE] })
  // @IsString({ always: true })
  // @Length(8, 20, { always: true })
  @Column()
  pwd: string

  @BeforeInsert()
  hashPassword() {
    console.log(this.pwd)  // when use @Exclude(), seems this.pwd was seted to undefined
    this.pwd = crypto.createHmac('sha256', this.pwd).digest('hex')
  }
}

It will recieve some error

So, can I use Exclude here?

adding {toPlainOnly: true} to @Exclude()`. it means “when i class DTO transforming to plain json string, i exclude this property.”

if this not work, adding interceptor ClassSerializerInterceptor at route. @UseInterceptors(ClassSerializerInterceptor)

https://docs.nestjs.com/techniques/serialization

Read more comments on GitHub >

github_iconTop Results From Across the Web

Exclude property of model in insert Entity Framework
Exclude a field/property from the database with Entity Framework 4 & Code-First. MS Doc on how to manually map properties to db fields:....
Read more >
Documentation: 15: CREATE TABLE - PostgreSQL
When a typed table is created, then the data types of the columns are determined by the underlying composite type and are not...
Read more >
Including and Excluding Objects from a Database
This page explains how to include and exclude objects from your database to a changelog file with the excludeObjects and includeObjects attributes.
Read more >
Create | GORM - GORM
Create a record and ignore the values for fields passed to omit. ... GORM will generate a single SQL statement to insert all...
Read more >
The Fluent API Ignore Method - Learn Entity Framework Core
Excluding an entity from mapping ... By convention, the AuditLog entity will be included in the model because it is referenced through a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found