繁体   English   中英

创建父文档时未初始化子文档。 Nestjs/猫鼬

[英]The subdocument is not initialized when the parent document is created. Nestjs/mongoose

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

PS 我希望 Ecdsa 成为用户 model 的一部分,而不是用户 model 的一部分,以拥有此文档的 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);

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

我刚改成:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM