-1

I have this DTO:

import { Expose, Type } from 'class-transformer';
import { UserDto } from '../../../admin/users/dtos/user.dto';

export class CompanyDto {
  constructor(partial: Partial<CompanyDto>) {
    Object.assign(this, partial);
  }

  @Expose()
  id!: number;

  @Expose()
  companyName!: string;

  @Expose()
  companyCode!: string;

  @Expose()
  country!: string;

  @Expose()
  headQuarter!: string;

  @Expose()
  @Type(() => UserDto)
  user!: UserDto;

  @Expose()
  createdBy!: string;

  @Expose()
  createdAt!: Date;
}

This is the object from the DB:

id: 12,
companyName: 'some company',
companyCode: '0001',
country: 'germany',
headQuarter: 'berlin',
createdAt: 2025-04-26T11:31:57.891Z,
user: User { userName: 'a12' }

I convert this into the DTO:

  plainToInstance(CompanyDto, new CompanyDto(company), {
    excludeExtraneousValues: true,
  }),

And I get a JSON like this:

"id": 12,
"companyName": "some company",
"companyCode": "0001",
"country": "germany",
"headQuarter": "berlin",
"user": {
    "userName": "a12"
},
"createdAt": "2025-04-26T11:31:57.891Z"

Instead of the user object, I only need a new property createdBy, which has the value of userName. I tried with getter, I tried with transform, no success. How can I get the content of the userName in the field createdBy?

There is no debug details, no errors, etc. I simply don't get in the JSON the createdBy field with its data.

0

2 Answers 2

0

You said that you tried with getter but wasn't successfull, I will quote what was said in this answer. plainToInstance will return an instance so you won't be able to see the computed getter property. To do so, use instanceToPlain which is meant to serialize that object.

Sign up to request clarification or add additional context in comments.

Comments

0

This did the trick:

 @Expose()
  @Transform(({ obj }) => obj.user.userName)
  createdBy!: string;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.