如何使用NestJS序列化返回id字符串而不是_bsontype

问题描述 投票:2回答:1

使用时

@UseInterceptors(ClassSerializerInterceptor)

就像它在文档here中解释的那样

我得到了所需的过滤结果,但是在使用mongodb时,id被格式化为_bsontype而不是正常的string,就像过去没有拦截器一样:

{
    "id": {
        "_bsontype": "ObjectID",
        "id": {
            "0": 92,
            "1": 108,
            "2": 182,
            "3": 85,
            "4": 185,
            "5": 20,
            "6": 221,
            "7": 12,
            "8": 56,
            "9": 66,
            "10": 131,
            "11": 172
        }
    },
    "createdAt": "2019-02-20T02:07:17.895Z",
    "updatedAt": "2019-02-20T02:07:17.895Z",
    "firstName": "The First Name",
    "lastName": "The Last Name",
    "email": "[email protected]"
}

如何将其转换回这样的普通id字符串?

{
    "id": "5c6cb655b914dd0c384283ac",
    "createdAt": "2019-02-20T02:07:17.895Z",
    "updatedAt": "2019-02-20T02:07:17.895Z",
    "firstName": "The First Name",
    "lastName": "The Last Name",
    "email": "[email protected]"
    "password": "okthen"
}
node.js typescript nestjs typeorm class-transformer
1个回答
3
投票

你可以使用class-transformer的@Transform()toPlainOnly选项:

import { Transform } from 'class-transformer';

@Entity()
export class User {
  @ObjectIdColumn()
  @Transform((value) => value.toString(), { toPlainOnly: true })
  _id: ObjectID;

ClassSerializerInterceptor内部使用类变换器的classToPlain()方法。

© www.soinside.com 2019 - 2024. All rights reserved.