class-transformer
class-transformer copied to clipboard
fix: Mongoose _id field transformed into a different one every time
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
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",
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
}