我的NestJS应用程序在使用ValidationPipe时调用mongoose时崩溃。当我从main.ts mongoose中注解验证器管道时,它工作正常。
这是我的主要的.ts代码,我注解了app.useGlobalPipes(新的验证管道());
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();
这是我的用户模式。
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);
它是我的用户控制器。
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);
// }
}
用户模块文件
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 {}
和我的用户服务文件
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;
}
}
}
1条答案
按热度按时间qv7cva1a1#
我知道现在很晚了,但这可能会帮助别人对我来说,诀窍是,改变这个:
更改为:
我注意到添加了Partial〈〉,至少这对我来说是这样的