javascript - 无法在关系 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
}
}
解决方案
你在这里提到
项目模型具有对类别模型的引用 (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 将起作用
推荐阅读
- vue.js - 用函数设置字典值?
- python - 如何根据数据框列的唯一值创建文本文件?
- c# - 为什么执行 exe 的 Control M OS Job 会在执行过程中卡住?
- python-3.x - Jupyter 与 Python 版本混合使用。内核使用 python 3.x 而不是 2.x
- apache-kafka - GenericJMXConfMBean:没有 MBean 匹配 ObjectName kafka.network:type=RequestMetrics,name=RequestsPerSec,request=Produce
- reactjs - 将文本字段 MUI 的占位符居中
- java - 无法让我的复制构造函数在我的简单代码中工作(我是 java 新手)
- r - 有没有办法使用 R 中的一个应用函数来优化这个循环?
- c - 字符串未显示在 C 的控制台中
- python - 简单的 Python 多线程网络服务器,带有 Asyncio 和在主函数中调用的事件