【问题标题】:How to reference other class correctly in typegoose (mongoose) and save reference (ObjectId) only?如何在 typegoose (mongoose) 中正确引用其他类并仅保存引用 (ObjectId)?
【发布时间】:2021-07-18 07:15:08
【问题描述】:

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

@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

【问题讨论】:

  • 请更新版本信息(typegoose、mongoose、typescript、mongodb)
  • @hasezoey 我已经在原始帖子中发布了我的版本。

标签: mongodb typescript mongoose nestjs typegoose


【解决方案1】:

我觉得应该是(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 的一部分

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 1970-01-01
    • 2018-07-15
    • 2021-02-25
    • 2015-02-10
    • 2014-03-18
    • 2014-09-11
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多