class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

fix: Mongoose _id field transformed into a different one every time

Open DoronTorangy opened this issue 2 years ago • 2 comments

Description

I have this class:

import { Expose } from 'class-transformer'
import { IsMongoId } from 'class-validator'
import { ObjectId } from 'mongodb'

export class MongoDocumentDto {
	@Expose()
	@IsMongoId()
	_id: ObjectId
}

When I try to transform a mongodb document into this dto the "_id" field is different every time

  const document = await mongoose.mymodel.findById(id)
  const dto = plainToInstance(MongoDocumentDto, document.toObject())
  console.asset(dto._id.toString() === id.toString())

I followed this issue and tried to implement Rush's solution:

But the Transform function cannot get 2 parameters, only 1 of type TransformFnParams (I use "class-transformer": "^0.5.1")

How can I solve this?

Expected behavior

"_id" to be transformed correctly

Actual behavior

"_id" is transformed wrongly

DoronTorangy avatar Apr 17 '22 06:04 DoronTorangy

The problem is in Symbols used as keys in ObjectId. I created a fix https://github.com/typestack/class-transformer/pull/1208

While it is not merged, you can use built version package.json: "class-transformer": "git+https://github.com/ClipboardHealth/class-transformer.git#0.5.2",

mentatxx avatar May 20 '22 07:05 mentatxx

Thanks @mentatxx I will check that for sure. For those who wait for it to be merged, until now I used this solution:

export function TransformMongoId(options?: ExposeOptions) {
  return (target: any, propertyKey: string) => {
	Transform((params) => params.obj[propertyKey]?.toString(), options)(target, propertyKey)
  }
}

export class MongoDocumentDto {
  @Expose()
  @TransformMongoId()
  @IsMongoId()
  _id: string
}

DoronTorangy avatar May 20 '22 09:05 DoronTorangy