【问题标题】:The subdocument is not initialized when the parent document is created. Nestjs/mongoose创建父文档时未初始化子文档。 Nestjs/猫鼬
【发布时间】:2021-05-19 19:22:52
【问题描述】:

创建用户时,子文档未使用默认值初始化。我只得到没有 ecdsa 字段的用户对象。你能告诉我哪里可能出错了吗?

附言我希望 Ecdsa 成为用户模型的一部分,而不是用户模型拥有此文档的 ID。有可能吗?

用户架构:

@Schema()
export class User {
  @Prop({required: true, unique: true })
  tgId: number;

  @Prop({default: "anonymus"})
  tgUsername: string;

  @Prop({default: Date.now()})
  registrationDate: Date;

  @Prop({default: () => ({})})
  ecdsa: Ecdsa;
}

export type UserDocument = User & mongoose.Document;
export const UserSchema = SchemaFactory.createForClass(User);

Ecdsa 架构:

@Schema()
export class Ecdsa {
  @Prop({default: 0}) //doesn't works
  operatorsCount: number;

  @Prop({
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'UserOperator'
    }],
    default: []
  })
  operators: UserOperator[];

  @Prop({default: 'test'}) //doesn't works
  test: string;
}

export type EcdsaDocument = Ecdsa & mongoose.Document;
export const EcdsaSchema = SchemaFactory.createForClass(Ecdsa);

【问题讨论】:

    标签: mongodb mongoose schema nestjs


    【解决方案1】:

    不确定这种方法是否正确,但它对我有用。现在用户内部的 ecdsa 对象在用户创建时初始化。

    我刚改成:

    @Prop({type: EcdsaSchema,
        default: () => ({})})
      ecdsa: EcdsaDocument;
    

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 1970-01-01
      • 2020-02-26
      • 2019-12-20
      • 1970-01-01
      • 2017-05-07
      • 2014-09-25
      • 2015-06-26
      • 2015-10-01
      相关资源
      最近更新 更多