猫鼬填充未提供合并结果

时间:2020-10-03 12:54:20

标签: node.js mongodb mongoose typegoose

我有两个模型,分别称为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");

2 个答案:

答案 0 :(得分:1)

扩展@Vishnu所说的:您有2.5个问题

  1. 对于populate,您需要使用字段名称而不是引用的模型名称
  2. 模型名称不是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");