无法使用关系nestjs/mongoose上的条件进行查询

dluptydi  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(386)

我有一个项目模型和一个类别模型。
项目模型具有对类别模型的引用(objectid)。
我正在编写代码来获取特定类别中的项目。
因此,我将类别的id作为参数(字符串类型)提供给服务,
然后写“returnthis.itemmodel.find({category:id}).exec();”。
其中,“类别”是对类别模型的引用,
“id”是传递给api调用的id。
我得到错误“没有重载匹配此调用”。
我怎样才能解决这个问题?
项目架构

  1. export type ItemDocument = Item & Document;
  2. @Schema({ timestamps: true })
  3. export class Item {
  4. @Prop()
  5. name_en: string;
  6. @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Category' })
  7. category: Category;
  8. }
  9. export const ItemSchema = SchemaFactory.createForClass(Item);

类别模式

  1. export type CategoryDocument = Category & mongoose.Document;
  2. @Schema({ timestamps: true })
  3. export class Category {
  4. @Prop()
  5. name_en: string;
  6. }
  7. export const CategorySchema = SchemaFactory.createForClass(Category);

类别.服务.ts

  1. @Injectable()
  2. export class CategoryService {
  3. constructor(
  4. @InjectModel(Category.name)
  5. private categoryModel: mongoose.Model<CategoryDocument>,
  6. @InjectModel(Item.name)
  7. private readonly ItemModel: mongoose.Model<ItemDocument>,
  8. ) {}
  9. findOneCatItems(id: string) {
  10. return this.ItemModel.find({category: id}).exec(); --> Error Line
  11. }
  12. }
daupos2t

daupos2t1#

你在这里提到
项目模型具有对类别模型的引用(objectid)。
但是 category 财产 Item 模型被键入为 Category .
执行此操作时: this.ItemModel.find({category: id}).exec(); 您提供的是一种 ObjectId 其中一种 Category 这是意料之中的事。
由于未在项目上保存整个类别对象,请将项目类中的定义更改为:

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

注意:如果你通过 id 作为一根绳子 this.ItemModel.find({category: id}).exec(); ,然后将category作为字符串而不是objectid键入即可

相关问题