0

我尝试仅在 mongo db 中保存 ObjectId 中的一些字段,但我发现以下内容无法正常工作:

@ObjectType()
export class User {
  @prop()
  @Field()
  name: string;

  @prop({ ref: () => OtherClassA })
  @Field()
  otherClassA: OtherClassA;

  @prop()
  @Field()
  otherClassB: OtherClassB;
}

@ObjectType()
export class OtherClassB {

  @prop()
  @Field()
  name: string;

  @prop({ ref: () => OtherClassB1 })
  @Field()
  otherClassB1: OtherClassB1;

  @prop({ ref: () => OtherClassB2 })
  @Field()
  otherClassB2: OtherClassB2;
}

我发现存储在 mongo db 中的数据如下:

user {
  _id
  name
  otherClassA: ObjectId("607910cdf9961b0dcf50b5d8")
  otherClassB {
    otherClassB1 {
      // the whole object of otherClassB1
    }
    otherClassB2 {
      // the whole object of otherClassB2
    }
  }
}

这不是我所期望的......

我期望:

user {
  _id
  name
  otherClassA: ObjectId("607910cdf9961b0dcf50b5d8")
  otherClassB {
    otherClassB1: ObjectId("607910cdf1231b0dcf51a456")
    otherClassB2: ObjectId("607910cdf1231b0dcf51a5bf")
  }
}

如何在 typegoose(mongoose) 中仅将引用保存在这种结构中?

2021-4-26 更新:

typegoose v7.6.0

猫鼬 v5.10.18

打字稿 v4.0.5

mongodb v3.6.6

4

1 回答 1

0

我认为应该是(Ref有区别):

import { prop, Ref} from '@typegoose/typegoose';

export class User {

  // ...

  @prop({ ref: () => OtherClassB1 })
  otherClassB1: Ref<OtherClassB1>;
}

链接:https ://typegoose.github.io/typegoose/docs/api/types/ref-type/

顺便说一句,我不知道是什么@Field(),但我认为它不是 Typegoose 的一部分

于 2022-01-11T15:07:29.207 回答