【问题标题】:why MongoDB returns a CastError when I am trying to delete an Item by id?当我尝试按 id 删除项目时,为什么 MongoDB 会返回 CastError?
【发布时间】:2022-01-24 00:28:27
【问题描述】:

我正在尝试创建 DELETE Rest API 方法,但出现 CastError。 问题在于它是 ObjectID 类型的 id,我将其设为数字​​,即使我选择了字符串,我也遇到了同样的错误。

错误

[Nest] 15504  - 22/12/2021, 21:34:11   ERROR [ExceptionsHandler] Cast to ObjectId failed for value "{ id: '61c32ba552a7cec272037b12' }" (type Object) at path "_id" for model "City"
CastError: Cast to ObjectId failed for value "{ id: '61c32ba552a7cec272037b12' }" (type Object) at path "_id" for model "City"
    at model.Query.exec (C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\mongoose\lib\query.js:4594:21)
    at CitiesService.deleteCity (C:\Users\ouss\Desktop\coffeeit-assessment\src\cities\cities.service.ts:46:64)
    at CitiesController.deleteCity (C:\Users\ouss\Desktop\coffeeit-assessment\src\cities\cities.controller.ts:25:31)
    at C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\@nestjs\core\router\router-execution-context.js:38:29
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\@nestjs\core\router\router-execution-context.js:46:28
    at C:\Users\ouss\Desktop\coffeeit-assessment\node_modules\@nestjs\core\router\router-proxy.js:9:17

cities.service.ts

@Delete(':id')
async deleteCity(id) {
    const result = await this.cityModel.deleteOne({ _id: id }).exec();

    if (!result) {
      throw new NotFoundException('Could not find city.');
    }
  }

cities.controller.ts

@Delete(':id')
  deleteCity(@Param() id: number) {
    return this.citiesService.deleteCity(id);
  }

city.model.ts

import * as mongoose from 'mongoose';

export const CitySchema = new mongoose.Schema({
  name: String,
  weather: mongoose.SchemaTypes.Mixed,
});

export interface City {
  id: number;
  name: string;
  weather: mongoose.Schema.Types.Mixed;
}

city.entity.ts

import { BaseEntity, Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class City extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  weather: any;
}

【问题讨论】:

  • deleteOne({ _id: id }) 中的id 应该是 ObjectId docs.mongodb.com/manual/reference/method/ObjectId 的一个实例,从控制器中的参数创建一个并将其传递给服务。
  • 可以用代码演示一下吗?
  • 我从未使用过nestjs,在javascript中它会是oid = new mongoose.Types.ObjectId(id);。您实际上可以尝试 this.cityModel.findByIdAndDelete mongoosejs.com/docs/api.html#model_Model.findByIdAndDelete 说它接受字符串 id 并隐式进行转换
  • 谢谢@Alex 我尝试在服务中转换 id const cityId = new ObjectId(id); 并且它工作得很好
  • 好东西!您是否介意将其格式化为答案并接受它,以向将来面临此问题的任何人说明解决方案是什么。

标签: mongodb mongoose nestjs mongoose-schema


【解决方案1】:

cities.service.ts

import { ObjectId } from 'mongodb';

...
@Delete(':id')
async deleteCity(id) {
    const cityId = new ObjectId(id); // Cast id to MongoDB Object id
    const result = await this.cityModel.deleteOne({ _id: cityId }).exec();

    if (!result) {
      throw new NotFoundException('Could not find city.');
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多