0

我正在使用 Typegoose v9.3.1

我需要使用Typegoose为具有非_id字段的另一个集合创建引用。

例如,我有以下型号。

类集合

export class Class {
  @prop({ required: true })
  public _id!: string;

  @prop({ required: true })
  public grade!: Source;

  @prop({ autopopulate: true, ref: Student, type: String })
  public students!: Ref<Student, string>[];
}

学生收藏

export class Student {
  @prop({ required: true })
  public rollNo!: string;

  @prop({ required: true })
  public name!: string;
}

从上面的示例类集合引用学生集合基于学生集合的_id字段(默认情况下)。但我需要基于rollNo字段(非 _id 字段)创建参考。

提前致谢!

4

1 回答 1

0

对于这种情况,我唯一知道的是虚拟填充:

我不知道有任何方法可以更改 prop-optionref使用的字段,所以我只能提供一个虚拟填充示例。

注意:此示例可能不适用于所有情况,例如您有特定的数据布局要求。

例子:

export class Class {
  @prop({ required: true })
  public _id!: string;

  @prop({ required: true })
  public grade!: Source;

  @prop({ autopopulate: true, ref: () => Student, foreignField: "classId localField: "_id" })
  public students!: Ref<Student, string>[];
}

export class Student {
  @prop({ required: true, ref: () => Class }) // this could also be done without "ref" and just setting the type to "ObjectId"
  public classId: Ref<Class>;

  @prop({ required: true })
  public rollNo!: string;

  @prop({ required: true })
  public name!: string;
}

如果上面的示例在您的情况下不起作用,那么我认为您唯一的选择是使用手动查询/聚合。

于 2022-01-20T12:28:30.787 回答