Open
Description
I was trying to...
When searching a list in nestJS, I want to convert each item to dto.
The problem:
However, the conversion works well when doing a detailed search, but the conversion is not applied when doing a list search as shown below.
Instead of participants, the length of participants must be entered in currentParticipantCount, and instead of rinkId, an object containing the id and name taken from the rink collection must be created.
However, the document is entered as is. How do I use it?
rental.service.ts
// detail
async get(@Param() postId: string): Promise<RentalPostDto> {
try {
const post = await this.rentalPostModel
.findOne({
_id: postId,
})
.populate('rinkId', 'name')
.lean();
return new RentalPostDto(post);
} catch (err) {
console.log({ err });
throw new Error(err);
}
}
// list
async getList(
@Query()
{ offset, limit, noun }: { offset: number; limit: number; noun?: Noun },
): Promise<{ list: RentalPostDto[]; isEnd: boolean }> {
try {
const filter = { ...(noun && { noun }) };
const rentalList = await this.rentalPostModel
.find(filter)
.populate('rinkId', 'name')
.skip(offset)
.limit(limit);
// .lean();
const totalCount = await this.rentalPostModel.countDocuments();
const list = [];
for (const data of rentalList) {
list.push(
new RentalPostDto((await data.populate('rinkId', 'name')).toObject()),
);
}
return {
list: list,
isEnd: offset + limit >= totalCount,
};
} catch (err) {
console.log({ err });
throw new Error(err);
}
}
rental.dto.ts
@Exclude()
export class RinkDto {
@Transform(({ obj }) => obj._id.toString())
@Expose()
id: string;
@IsString()
@Expose()
readonly name: string;
}
export class RentalPostDto {
@Transform(({ obj }) => obj._id.toString())
@Expose()
id: string;
@IsEnum(Noun)
readonly noun: Noun;
@Transform(({ obj }) => obj.rinkId)
@Type(() => RinkDto)
@Expose()
readonly rink: RinkDto;
@Exclude()
rinkId: string;
@IsNumber()
readonly totalParticipantCount: number;
@Transform(({ obj }) => obj.participants.length)
@Expose()
@IsNumber()
currentParticipantCount: number;
@Exclude()
participants?: string[];
@ValidateNested()
@Type(() => PriceInfoDto)
readonly priceInfo: PriceInfoDto;
@ValidateNested()
@Type(() => ReservationDateDto)
readonly reservationDates: ReservationDateDto[];
@IsString()
readonly description?: string;
@IsString()
readonly externalChattingUrl: string;
@Exclude()
_id: string;
@Exclude()
__v: number;
constructor(data: RentalPost) {
Object.assign(this, data);
}
}