How to use MongoDB query operators in TypeScript DTO with class-validator?

29 views Asked by At

Here is what I want to achieve. My current QueryUserDto is:

import { ApiHideProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import {
  IsEmpty,
  IsEnum,
  IsMongoId,
  IsOptional,
  IsString,
} from 'class-validator';
import { QueryModifierDto } from 'src/common/dtos/query-modifier.dto';

export class QueryUserDto extends QueryModifierDto {
  @IsOptional()
  @IsMongoId()
  _id?: string;

  @IsOptional()
  @IsString()
  firstName?: string;

  @IsOptional()
  @IsString()
  lastName?: string;

  @IsOptional()
  @Transform(({ value }) => value.toLowerCase())
  @IsString()
  email?: string;

  @IsOptional()
  @IsEnum(['admin', 'user'], { message: 'Role must be either admin or user' })
  role?: string;

  @ApiHideProperty()
  @IsOptional()
  @IsEmpty()
  tokens?: string[];
}

it doesn't allow me to write queries that include MongoDB query operators like:

const user = await this.usersService.findOne({
  tokens: { $in: [payload.token] },
});

the $in operator is just an example. I should be able to write any valid MongoDB operator here.

note: At the same time, the query (from the client side) should not be affected.

And I am also attaching QueryModifierDto (QueryUserDto extends QueryModifierDto) here if it helps.

import { IsNumber, IsOptional, IsPositive, IsString } from 'class-validator';

export class QueryModifierDto {
  @IsOptional()
  @IsPositive()
  @IsNumber()
  page?: number;

  @IsOptional()
  @IsPositive()
  @IsNumber()
  limit?: number;

  @IsOptional()
  @IsString()
  fields?: string;

  @IsOptional()
  @IsString()
  sort?: string;
}
0

There are 0 answers