Search code examples
node.jstypescriptnestjstypeormclass-transformer

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


When using

@UseInterceptors(ClassSerializerInterceptor)

like it is explained in the Documentation here

I get the desired filtered result, however while using mongodb the id is formatted in _bsontype instead of a normal string like it used to be without the interceptor like this:

{
    "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]"
}

How can I convert it back to a normal id string like this?

{
    "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"
}

Solution

  • You can use class-transformer's @Transform() with the option toPlainOnly:

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

    The ClassSerializerInterceptor internally uses class-transformer's classToPlain() method.