NestJs Mongoose保存文档触发ValidationError:必填字段缺失
问题:Mongoose保存文档时触发必填字段验证错误
错误详情
ValidationError: Problem validation failed: creator: Path `creator` is required., description: Path `description` is required., title: Path `title` is required.
相关代码与请求信息
Schema定义
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { HydratedDocument } from 'mongoose'; export type ProblemDocument = HydratedDocument<Problem>; @Schema() export class Problem { @Prop({ required: true }) title: string; @Prop({ required: true }) description: string; @Prop({ required: true }) creator: string; @Prop() ideas: string[]; @Prop() createdAt: Date; @Prop() updatedAt: Date; @Prop() deletedAt: Date; } export const ProblemSchema = SchemaFactory.createForClass(Problem);
Problems服务create方法
async create(createProblemDto: CreateProblemDto): Promise<any> { try { console.log(createProblemDto); const problem = new this.ProblemModel({ createProblemDto }); return problem.save(); } catch (error) { throw error; } }
CreateProblemDto定义
import { IsString, IsNotEmpty } from 'class-validator'; export class CreateProblemDto { @IsString({ message: 'Title must be a string' }) @IsNotEmpty({ message: 'Title is required' }) title: string; @IsString({ message: 'Description must be a string' }) @IsNotEmpty({ message: 'Description is required' }) description: string; @IsString({ message: 'Creator must be a string' }) @IsNotEmpty({ message: 'Creator is required' }) creator: string; }
请求信息
POST http://localhost:3000/problems Content-Type: application/json
{ "title": "hello", "description": "world", "creator": "john_doe" }
控制台日志
{ createProblemDto: { title: 'hello', description: 'world', creator: 'john_doe' } } [Nest] 17591 - 01/02/2024, 6:00:27 PM ERROR [RpcExceptionsHandler] Problem validation failed: creator: Path `creator` is required., description: Path `description` is required., title: Path `title` is required. ValidationError: Problem validation failed: creator: Path `creator` is required., description: Path `description` is required., title: Path `title` is required. at model.Document.invalidate (/home/arta/project/vsCode/nestjs/devProblem/problems/node_modules/.pnpm/mongoose@8.0.3/node_modules/mongoose/lib/document.js:3187:32) at /home/arta/project/vsCode/nestjs/devProblem/problems/node_modules/.pnpm/mongoose@8.0.3/node_modules/mongoose/lib/document.js:2980:17 at /home/arta/project/vsCode/nestjs/devProblem/problems/node_modules/.pnpm/mongoose@8.0.3/node_modules/mongoose/lib/schemaType.js:1368:9 at processTicksAndRejections (node:internal/process/task_queues:77:11)
解决方案
问题出在创建Mongoose模型实例时的参数传递错误:
// 错误写法:将createProblemDto作为嵌套对象传入 const problem = new this.ProblemModel({ createProblemDto }); // 正确写法:直接传入createProblemDto,或者展开对象 const problem = new this.ProblemModel(createProblemDto); // 或者 const problem = new this.ProblemModel({ ...createProblemDto });
原因说明
控制台日志显示,createProblemDto被包裹在一个同名的键下,导致Mongoose无法找到Schema中定义的顶层title、description、creator字段,因此触发必填字段的验证失败。直接传入对象(或展开对象)可以确保字段正确映射到Schema定义的路径上。
内容的提问来源于stack exchange,提问作者arta
相关产品推荐
相关产品推荐

