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

How do I return an id string instead of a _bsontype with NestJS Serialization

使用时

@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": "giberish@gmail.com"
}

如何将它转换回像这样的普通 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": "giberish@gmail.com"
    "password": "okthen"
}

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

import { Transform } from 'class-transformer';

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

ClassSerializerInterceptor内部使用class-transformer的classToPlain()方法。