繁体   English   中英

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

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

使用时

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

您可以将class-transformer的@Transform()toPlainOnly选项toPlainOnly

import { Transform } from 'class-transformer';

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM