猫鼬填充未提供连接结果
Mongoose populate not provided joined result
我有两个名为 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);
我正在尝试填充连接数据,但我没有得到连接数据 result.it 只包含 product._id.
这是我的代码
let data = await TodaysDealModel.find().populate("ProductsModel");
您应该为 populate
方法提供 TodaysDealModel
模型中提供的字段名称。
尝试
let data = await TodaysDealModel.find().populate("products");
扩展@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();
我有两个名为 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);
我正在尝试填充连接数据,但我没有得到连接数据 result.it 只包含 product._id.
这是我的代码
let data = await TodaysDealModel.find().populate("ProductsModel");
您应该为 populate
方法提供 TodaysDealModel
模型中提供的字段名称。
尝试
let data = await TodaysDealModel.find().populate("products");
扩展@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();