NestJS Mongoose schema error when use validator pipe

Viewed 776

My NestJS app has crashed when use call mongoose when use ValidationPipe. When I comment validator pipe from main.ts mongoose works

This is my main.ts code, that i comment app.useGlobalPipes(new ValidationPipe());

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';


    async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const config = new DocumentBuilder()
    .setTitle('ADS_BANK')
    .setDescription('The ADS_BANK API')
    .setVersion('1.0')
    .addTag('adsBank')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  app.enableCors({
    origin: '*',
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
  });
  // app.useGlobalPipes(new ValidationPipe());
  await app.listen(3002);
}
bootstrap();

this is my user schema.

import { UserRole } from '../shared/enums/user.role';

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsNotEmpty, Length } from 'class-validator';

@Schema({ timestamps: true, validateBeforeSave: true })
export class User extends Document {
  @ApiProperty()
  @Prop({
    required: [true, 'نام اجباری است'],
  })
  firstName: string;

  @ApiProperty()
  @Prop({ required: [true, 'نام خانوادگی اجباری است'] })
  lastName: string;

  @ApiProperty()
  @Prop({
    required: [true, 'نام کاربری اجباری است'],
    unique: [true, 'نام کاربری تکراری است'],
  })
  username: string;

  @ApiProperty()
  @Prop({
    required: [true, 'شماره موبایل اجباری است'],
    unique: [true, 'شماره موبایل تکراری است'],
  })
  phoneNumber: string;

  @ApiProperty()
  @Prop({ required: [true, 'گذر واژه اجباری است'] })
  password: string;

  @ApiProperty()
  @Prop({ unique: [true, 'ایمیل تکراری است'] })
  email: string;

  @ApiProperty()
  @Prop({ required: [true, 'رول اجباری است'] })
  role: UserRole;
}

export const UserSchema = SchemaFactory.createForClass(User);

and its my user controller.

import {
  Get,
  Controller,
  Put,
  Post,
  Body,
  Param,
  Delete, UsePipes, ValidationPipe,
} from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.schema';
import { ApiImplicitParam } from '@nestjs/swagger/dist/decorators/api-implicit-param.decorator';

@Controller('user')
export class UserController {
  constructor(private readonly service: UserService) {}

  @Post()
  async create(@Body() model: User) {
    return await this.service.create(model);
  }

  @Get()
  async get() {
    return await this.service.get();
  }

  @Get(':id')
  @ApiImplicitParam({ name: 'id', type: String })
  async getOne(@Param('id') id) {
    return await this.service.getOne(id);
  }

  // @Delete(':id')
  // async remove(@Param('id') id) {
  //   return await this.service.remove(id);
  // }
}

user module file

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose/dist/mongoose.module';
import { UserSchema } from './user.schema';
import { UserController } from './user.controller';
import { UserService } from "./user.service";
import { SharedModule } from "../shared/shared.module";

@Module({
  imports: [
    SharedModule,
    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
  ],
  providers: [UserService],
  exports:[UserService],
  controllers: [UserController],

})
export class UserModule {}

and my user service file

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User } from './user.schema';
import { BcryptHandler } from "../shared/handler/bcrypt.handler";

@Injectable()
export class UserService {
  constructor(@InjectModel(User.name) private readonly model: Model<User>,
                private bcryptHandler:BcryptHandler) {}

  async get(): Promise<User[]> {
    return await this.model.find().exec();
  }

  async getOne(id:string): Promise<User> {
    return await this.model.findOne({_id:id}).exec();
  }

  async getByUsername(username:string): Promise<User> {
    return await this.model.findOne({username:username}).exec();
  }

  async create(model: User): Promise<User> {
    model.password= await this.bcryptHandler.createHashPassword(model.password);
    const user = await new this.model(model);
    return await user.save();
  }

  async update(id: string, model: User): Promise<User> {
    return this.model.findByIdAndUpdate(id, model);
  }

  async remove(id: string): Promise<boolean> {
    try {
      await this.model.findOneAndDelete({ _id: id });
      return true;
    } catch (e) {
      return e;
    }
  }
}
0 Answers
Related