【问题标题】:Can't query with condition on relation nestjs/mongoose无法在关系 nestjs/mongoose 上查询条件
【发布时间】:2021-09-19 21:29:18
【问题描述】:

我有一个 Item 模型和一个 Category 模型。
item 模型对 Category 模型有一个reference (ObjectId)。 我正在编写代码来获取特定类别中的项目
所以我将类别的 id 作为服务的参数(字符串类型),
然后写“return this.ItemModel.find({category: id}).exec();”。
其中“类别”是对类别模型的引用,
'id' 是传递给 API 调用的 id。
我收到错误“No Overload Matches This Call”。

我该如何解决这个问题?

项目架构

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);

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
  }
}

【问题讨论】:

标签: javascript mongoose nestjs nestjs-mongoose


【解决方案1】:

你在这里提到

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

Item 模型的category 属性被键入为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();,则将category 作为字符串而不是ObjectId 将起作用

【讨论】:

  • 非常感谢!这似乎有效!但在文档中,该示例使用类(在示例中,它是 Owner),而不是 mongoose.Schema.Types.ObjectId。这两者有什么区别?
猜你喜欢
  • 2022-01-15
  • 2021-09-08
  • 1970-01-01
  • 2021-05-03
  • 2022-06-15
  • 2021-08-30
  • 2019-11-12
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多