【问题标题】:Nestjs ClassSerializerInterceptor doesn't display _idNestjs ClassSerializerInterceptor 不显示_id
【发布时间】:2022-01-23 04:36:15
【问题描述】:

我在使用序列化程序正确公开 _id 时遇到问题。

我用:

@UseInterceptors(ClassSerializerInterceptor)
@SerializeOptions({ strategy: 'excludeAll' })

定义的类:

export class UpdatedCounts {
    @Expose()
    _id: ObjectId;
    @Expose()
    aCount: number;
    @Expose()
    bCount: number;

    constructor(partial: Partial<MyDocument>) {
        Object.assign(this, partial);
    }
}

console.log() 中的对象在它通过序列化器之前运行

{
  _id: new ObjectId("61c2256ee0385774cc85a963"),
  bannerImage: 'placeholder2',
  previewImage: 'placeholder',
  aCount: 1,
  bCount: 0,
}

返回的对象:

{
  "_id": {},
  "aCount": 1,
  "bCount": 0
}

那么我的_id怎么了?

我尝试使用字符串类型而不是 ObjectId,但这也不起作用

我不想使用@Exclude,因为我在示例 console.log() 中遗漏了另外 10 个道具,排除所有道具并只使用这 3 个应该更容易

【问题讨论】:

  • 尝试在_id 字段上使用@Type(() =&gt; ObjectId)
  • @MicaelLevi 我让另一个人告诉我同样的事情,但不幸的是,这不起作用,如果我做错了,我知道 =,=
  • 我不知道。我从未尝试过使用内置序列化程序,tbh。我改用automapperts.netlify.app

标签: javascript node.js mongodb mongoose nestjs


【解决方案1】:

只需使用@Transform:

@Expose()
@Transform((params) => params.obj._id.toString())
_id: ObjectId;

您不能只使用 JSON 发送 ObjectId。您必须将其转换为字符串。

【讨论】:

  • 啊是的,这行得通,非常感谢,在看到我必须使用“obj”之前我失败了
猜你喜欢
  • 2021-04-15
  • 2020-12-11
  • 2019-09-07
  • 2022-08-12
  • 1970-01-01
  • 2020-07-03
  • 2022-10-06
  • 2021-03-27
  • 2023-03-26
相关资源
最近更新 更多