当我在DTO中将变量作为id和_id进行检查时,在JSON响应中获得了不同的ID值
情况一(使用id作为变量)
响应的DTO
export class UserDetail {
@Expose( )
id: string; //HERE ID is used which gives original id as in db
@Expose( )
name: string;
@IsOptional( )
@Expose( )
mobile: string;
}
对此的响应是:
{
"id": "6229df5cc32d3aaef32525e0", // Correct id as in db
"name": "Name1 Title1",
"mobile": "AB391C339",
},
{
"id": "6229df7bc32d3aaef32525e3", // Correct id as in db
"name": "Name2 Title2",
"mobile": "CDE393F339",
}
案例 II (使用 _id 作为变量)
现在修改 DTO
export class UserDetail {
@Expose( )
_id: string; //HERE _id is used which gives different id value from original one and subsequent ids are in incremental fashion
@Expose( )
name: string;
@IsOptional( )
@Expose( )
mobile: string;
}
回应如下:
{
"_id": "624023c8193f2404f8312ccb", // Not same as present in db
"name": "Name1 Title1",
"mobile": "AB391C339"
},
{
"_id": "624023c8193f2404f8312ccc", // Not same as present in db
"name": "Name2 Title2",
"mobile": "CDE393F339"
},
用户架构如下:
@Schema( )
export class User extends Document {
@Prop( { required: true } )
name: string;
@Prop( { required: true } )
mobile: string;
}
另一个观察结果:在dto中使用_id
,响应中的所有id都是递增的。例如:cb,cc,cd,ce
而只使用id
,则显示数据库中的原始id
。
使用的库和框架:NestJs、Fastify、Mongoose、Class-Transformer