【问题标题】:Nest JS - Client validation failed : Path is requiredNest JS - 客户端验证失败:需要路径
【发布时间】:2022-01-17 09:06:28
【问题描述】:

我在这里发帖是因为我已经被一个问题困住了几个小时。 我正在使用 Nest JS 8 和 MongoDB 创建一个 API,并使用 Postman 对其进行测试。当我想执行 POST 请求 (http://localhost:3000?nom=Antoine) 以在我的数据库中插入一个对象时,我收到一条错误消息(500:内部服务器错误),显示“客户端验证失败:nom:路径 'nom' 是必需的(nom 是我的对象属性的名称)。

我已经浏览了有关此类问题的所有主题,尝试升级我的 Nest 版本,使用中间件,以确保安装了每个依赖项的正确版本。

我不想删除“required: true”属性,因为我认为这是必要的。我尝试将其设置为“false”,这使我能够在数据库中插入对象,但没有我的属性“nom”(法语名称)。

如果你们有任何帮助,这是我的架构:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type ClientDocument = Client & Document;

@Schema()
export class Client {
  @Prop({ required: true })
  nom: string;
}

export const ClientSchema = SchemaFactory.createForClass(Client);

这是我的控制器:

import { Body, Controller, Delete, Get, Param, Post, Put} from '@nestjs/common';
import { ClientService } from './client.service';
import { ClientDto } from './dto/client.dto';
import { CreateClientDto } from './dto/create-client.dto';
import { UpdateClientDto } from './dto/update-client.dto';

@Controller('/client')
export class ClientController {
    constructor(private readonly clientService: ClientService) {}

    @Get()
    async index(){
        return await this.clientService.findAll();
    }

    @Get(':id')
    async find(@Param('id') id: string) {
        return await this.clientService.findOne(id);
    }

    @Post()
    async create(@Body() createClientDto: CreateClientDto) {
        console.log(createClientDto);
        return await this.clientService.create(createClientDto);
    }

    @Put(':id')
    async update(@Param('id') id: string, @Body() updateClientDto: ClientDto) {
        return await this.clientService.update(id, updateClientDto);
    }

    @Delete(':id')
    async delete(@Param('id') id: string) {
        return await this.clientService.delete(id);
    }
}

感谢收看

【问题讨论】:

  • 请编辑您的问题以添加您从邮递员发送的请求。
  • 你从console.log(createClientDto);得到什么?
  • 我得到:{ « nom »: « Antoine » } 这对我来说似乎是正确的

标签: node.js typescript mongodb mongoose nestjs


【解决方案1】:

我找到了解决方案(我仍然不知道为什么会这样)。

在我的 client.service.ts 中,我从这里更新了 create 函数:

async create(createClientDto: CreateClientDto): Promise<Client> {
        return await new this.model({createClientDto}).save();
    }

到这里

async create(createClientDto: CreateClientDto): Promise<Client> {
    return await new this.model({
      ...createClientDto,
      createdAt: new Date(),
    }).save();
  }

感谢您花时间回答,希望对您有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 2022-12-14
    • 2018-03-29
    • 2021-10-07
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多