我有两个模型,分别称为TodaysDeals和Products
export class TodaysDeal {
_id: ObjectId;
@Property({ required: true, type: Schema.Types.ObjectId, ref: "ProductsModel" })
products: Products
}
export const TodaysDealModel = getModelForClass(TodaysDeal);
和
export class Products {
_id: ObjectId;
@Property({ required: true })
productName: String;
}
export const ProductsModel = getModelForClass(Products);
我正在尝试填充联接的数据,但没有得到联接的结果。它只包含product._id。
这是我的代码
let data = await TodaysDealModel.find().populate("ProductsModel");
答案 0 :(得分:1)
扩展@Vishnu所说的:您有2.5个问题
populate
,您需要使用字段名称而不是引用的模型名称 ProductsModel
,至少不是您的代码示例提供的模型名称look here to see how typegoose generates class/model names and here 另一个“较小”的问题是,您使用Products
作为类型,其中Ref<Products>
是正确的
您纠正后的代码如下:
export class TodaysDeal {
_id: ObjectId;
@Property({ required: true, type: Schema.Types.ObjectId, ref: "Products" })
products: Ref<Products>;
}
export const TodaysDealModel = getModelForClass(TodaysDeal);
export class Products {
_id: ObjectId;
@Property({ required: true })
productName: String;
}
export const ProductsModel = getModelForClass(Products);
let data = await TodaysDealModel.find().populate("products").exec();
答案 1 :(得分:0)
您应为populate
方法提供TodaysDealModel
模型中提供的字段名称。
尝试
let data = await TodaysDealModel.find().populate("products");