4

I have an issue properly exposing the _id using the Serializer.

I use:

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

The defined Class:

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

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

The object in console.log() before it runs through the Serializer

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

The object being returned:

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

So what happened to my _id?

I tried using string type instead of ObjectId but that also does not work

I do not want to use @Exclude since there are 10 more props which I left out in the example console.log(), and it should be easier to exclude all and just use these 3

3
  • 1
    try using @Type(() => ObjectId) on _id field Commented Dec 21, 2021 at 20:20
  • @MicaelLevi I had another person tell me the same thing, but unfortunately that does not work, idk if I am doing it wrong =,= Commented Dec 22, 2021 at 0:58
  • I can't tell. I've never tried using the builtin serializer, tbh. I'm using automapperts.netlify.app instead Commented Dec 22, 2021 at 1:37

1 Answer 1

4

Just use @Transform:

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

You can not just send ObjectId with JSON. You must convert it to a string.

1
  • 1
    Ah yes this worked, thank you very much, I failed before seeing that I have to use the "obj" Commented Dec 22, 2021 at 1:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.