首页 > 解决方案 > 无法在关系 nestjs/mongoose 上查询条件

问题描述

我有一个项目模型和一个类别模型。 项目模型具有对类别
模型 的引用(ObjectId) 。 我正在编写代码来获取特定类别中的项目。 因此,我将类别的 id 作为参数(字符串类型)获取到服务, 然后编写“return this.ItemModel.find({category: id}).exec();”。 其中“category”是对 Category 模型的引用, “id”是传递给 API 调用的 id。 我收到错误“没有重载匹配此调用”。





我该如何解决这个问题?

项目架构

export type ItemDocument = Item & Document;
@Schema({ timestamps: true })
export class Item {
  @Prop()
  name_en: string;
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Category' })
  category: Category;
}
export const ItemSchema = SchemaFactory.createForClass(Item);

类别架构

export type CategoryDocument = Category & mongoose.Document;
@Schema({ timestamps: true })
export class Category {
  @Prop()
  name_en: string;
}
export const CategorySchema = SchemaFactory.createForClass(Category);

类别.service.ts

@Injectable()
export class CategoryService {
  constructor(
    @InjectModel(Category.name)
    private categoryModel: mongoose.Model<CategoryDocument>,
    @InjectModel(Item.name)
    private readonly ItemModel: mongoose.Model<ItemDocument>,
  ) {}
  findOneCatItems(id: string) {
    return this.ItemModel.find({category: id}).exec(); --> Error Line
  }
}

标签: javascriptmongoosenestjsnestjs-mongoose

解决方案


你在这里提到

项目模型具有对类别模型的引用 (ObjectId)。

但模型的category属性Item类型为Category.

当你这样做时: this.ItemModel.find({category: id}).exec();

您正在提供一种类型,ObjectId其中一种类型Category是预期的。

由于您没有将整个类别对象保存在一个项目上,请将您的 Item 类中的定义更改为:

@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Category' })
  category: mongoose.Schema.Types.ObjectId;

注意:如果您在id此处作为字符串传递,则将this.ItemModel.find({category: id}).exec();类别输入为字符串而不是 ObjectId 将起作用


推荐阅读