3

使用时

@UseInterceptors(ClassSerializerInterceptor)

就像这里的文档中解释的那样

我得到了所需的过滤结果,但是在使用 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"
}
4

1 回答 1

5

@Transform()您可以使用带有选项的类转换器toPlainOnly

import { Transform } from 'class-transformer';

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

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

于 2019-02-20T06:29:59.197 回答