Search code examples
node.jstypescriptserializationnestjsclass-transformer

How can I change the property name of a serialized entity with toJSON?


I want to serialize a property with a different name than it has in the entity.

@Entity()
export class MyEntity {
  // This should be serialized with name_column in JSON
  @Column()
  name: string
}

When I call classToPlain I want the property name to be serialized to name_column:

classToPlain(myEntity)
// returns: {name: 'my name'}
// should be: {name_column: 'my name'}

Solution

  • Is there a specific reason you are using json-typescript-mapper instead of class-transformer, which is natively supported by nest.js?


    With class-transformer, you can change the name of a column with @Expose:

    @Expose({ name: "name_column" })
    name: string;
    

    For the serialization, you can just annotate your controller class or individual methods with @UseInterceptors(ClassSerializerInterceptor). With the annotation, it will automatically serialize all entities, that you return from a controller method. You can read more about this in this thread.