【问题标题】:mongo object id is not generating inside object of arraymongo 对象 id 未在数组的对象内部生成
【发布时间】:2021-09-08 20:03:39
【问题描述】:

我在后端使用nestJs,并且我有一个以数组作为属性的模式。出于某种目的,我需要每个数组属性的对象 id,但没有生成 id。

数组内对象的 DTO:

export class EmergencyContact {
 @Prop({ _id: true })
 _id: string;

 @Prop()
 @ApiProperty()
 @IsNotEmpty()
 title: string;

 @Prop()
 @ApiProperty()
 @IsNotEmpty()
 contactNumber: string;

 @Prop()
 status: boolean;
}

架构 DTO:

@Schema({ timestamps: true })
export class EDiary {
  _id: string;

  @Prop()
  @ApiProperty()
  @IsNotEmpty()
  state: string;

  @ApiProperty()
  @Prop()
  @Type(() => EmergencyContact)
  emergencyContact: EmergencyContact[];
}

【问题讨论】:

    标签: node.js mongodb nestjs


    【解决方案1】:

    在互联网上进行研究后,我找到了解决上述问题的一种方法。为了获取内部的 MongoDB 对象 ID,我对 DTO 进行了以下更改。

    export class EmergencyContact {
     @Prop()
     _id: string;
    
     @Prop()
     @ApiProperty()
     @IsNotEmpty()
     title: string;
    
     @Prop()
     @ApiProperty()
     @IsNotEmpty()
     contactNumber: string;
    
     @Prop()
     status: boolean;
    }
    
    
    @Schema({ timestamps: true })
    export class EDiary {
      _id: string;
    
      @Prop()
      @ApiProperty()
      @IsNotEmpty()
      state: string;
    
      @ApiProperty()
      @ApiProperty()
      @Prop([{
        title: {
          type: String
        },
        contactNumber: {
          type: String
        }, status: {
          type: Boolean
        }
      }])
      @Type(() => EmergencyContact)
      emergencyContact: EmergencyContact[];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多