How to reference other class correctly in typegoose (mongoose) and save reference (ObjectId) only?

1k Views Asked by At

I try to save some of fields in ObjectId only in the mongo db, but I find the following not working correctly:

@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;
}

I found the data stored in the mongo db as following:

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

which is not what I expected....

I expected:

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

How can I save the reference only in such structure in typegoose(mongoose)?

2021-4-26 Updated:

typegoose v7.6.0

mongoose v5.10.18

typescript v4.0.5

mongodb v3.6.6

1

There are 1 best solutions below

1
On

I think it should be (Ref is the difference):

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

export class User {

  // ...

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

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

BTW, I don't know what @Field() is, but I don't think it's part of Typegoose