Typegoose-引用子文档的ObjectId

时间:2019-06-19 02:26:29

标签: mongodb typescript mongoose

我正在尝试从子文档中提取ref。文档看起来像这样。

样本类别文档:

{
  "_id": 12345
  "keyword": "smart phones",
  "subCategories": [
    {
      "_id": 6789,
      "keyword": "apple"
    },
    {
      "_id": 101123,
      "keyword": "samsung"
    }
  ]
}

示例词典文档:

{
  "_id": 12345
  "keyword": "iPhone",
  "category": 12345,
  "subCategory": 6789
}

这是我尝试对Typegoose模型定义进行的操作:

对于字典(请注意subCategory道具,我不确定这是否是引用子文档的正确方法):

export class Dictionary extends Typegoose {
  _id!: Schema.Types.ObjectId;

  @prop({
    default: 1
  })
  type!: IDictionaryInput['type'];

  @prop()
  mainKeyword!: string;

  @arrayProp({ items: Synonym })
  synonyms!: Synonym[];

  @prop({ ref: Category })
  category!: Ref<Category>;

  @prop({ ref: CategoryModel.subCategories })
  subCategory!: Ref<Subcategory>;

  @prop({
    default: true
  })
  status!: IDictionaryInput['status'];
}

对于类别:

export class Category extends Typegoose {
  _id!: Schema.Types.ObjectId;

  @prop()
  keyword!: ICategoryInput['keyword'];

  @prop({
    default: 1
  })
  type!: ICategoryInput['type'];

  @arrayProp({ items: Subcategory })
  subCategories!: Subcategory[];

  @prop({
    default: true
  })
  status!: ICategoryInput['status'];

  @prop()
  insertTimestamp!: ICategoryInput['insertTimestamp'];
}

然后我尝试通过以下操作populate进行引用:

DictionaryModel.findOne({ _id: id })
    .populate({
      path: 'category',
      model: CategoryModel
    })
    .populate({
      path: 'subCategory',
      model: CategoryModel.subCategories
    });

我可以成功地从category填充引用,但不能在subCategory上填充引用。

0 个答案:

没有答案