尝试在 nestjs 上写一个 get 请求以按任务名称搜索

问题描述 投票:0回答:0

我正在尝试在 nestjs 上写一个 get 请求以按名称搜索。

@Controller('tasks') //Decorator tasks
export class TasksController {
  constructor(private readonly tasksService: TasksService) {} //injecte. Delegate our service from ./tasks.service

  @Post()
  @HttpCode(HttpStatus.CREATED) //Catched error and output number error. CREATED it error 201
  @Header('Cache-Control', 'none') //Adds Header
  create(@Body() createTasks: CreateTasksDto): Promise<Task> {
    return this.tasksService.create(createTasks);
  }

  @Get()
  getAll() {
    return this.tasksService.getAll(), console.log('Work');
  }

  // @Get()
  // // @Redirect('https://youtube.com', 301) //Redirect in case of an error 301
  // getAll() {
  //   return 'getAll'
  // }

  @Get(':id') //Get dinamic param id from Request Route Parameters
  getOne(@Param('id') id: ObjectId) {
    return this.tasksService.getOne(id);
  }

  @Delete(':id') //Get dinamic param id from Request Route Parameters
  remove(@Param('id') id: ObjectId) {
    return this.tasksService.remove(id);
  }

  @Put(':id')
  update(@Body() updateTask: UpdateTasksDto, @Param('id') id: string) {
    // For update we creat separately update DTO ./dto/update-tasks.dto
    return this.tasksService.update(updateTask, id);
  }

  @Get('search')
  search(@Query('query') query: string): Promise<Task[]> {
    return this.tasksService.search(query);
  }
}
@Injectable()
export class TasksService {
  constructor(@InjectModel(Task.name) private taskModel: Model<TaskDocument>) {}

  async getAll(): Promise<Task[]> {
    const tasks = await this.taskModel.find();
    return tasks;
  }

  async getOne(id: ObjectId) {
    const task = await this.taskModel.findById(id);
    return task;
  }

  async create(tasksDto: CreateTasksDto): Promise<Task> {
    const newTask = await this.taskModel.create(tasksDto);
    return newTask;
  }

  async remove(id: ObjectId) {
    const task = await this.taskModel.findByIdAndDelete(id);
    return task;
  }

  async update(updateTask: UpdateTasksDto, id: string) {
    return this.taskModel.findByIdAndUpdate(id, updateTask);
  }

  async search(query): Promise<Task[]> {
    const tasks = await this.taskModel.find({
      task: { $regex: new RegExp(query, 'i') },
    });
    return tasks;
  }
}

我不明白为什么会出现错误 “错误 [ExceptionsHandler] 访问 该对象因路径“_id”上的值“搜索”(类型字符串)而失败 “任务”模型 施法者错误:投射到 ObjectId 失败 对于“任务”模型的路径“_id”的值“搜索”(类型字符串)“

在 Postman 中,它在 GET 请求链接时输出错误 500 http://localhost:3000/任务/搜索 http://localhost:3000/search

node.js search nestjs
© www.soinside.com 2019 - 2024. All rights reserved.