class-transformer: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

Hello,

My code

public async findOne<T>(cls: ClassType<T>, query:any): Promise<T> {
    let collectionName = Reflect.getMetadata('collectionName', cls);
    let collection = this.mongo.collection(collectionName);
    let json: {} = await collection.findOne(query); // -> returns plain js object
    if(json === null) return null;
    return plainToClass(cls, json);
}

When i use this, it works just fine

    return deserialize(cls, JSON.stringify(json));

Error

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
    at fromObject (buffer.js:274:9)
    at Function.Buffer.from (buffer.js:106:10)
    at new Buffer (buffer.js:85:17)
    at TransformOperationExecutor.transform (/home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:77:32)
    at _loop_1 (/home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:146:45)
    at TransformOperationExecutor.transform (/home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:169:17)
    at _loop_1 (/home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:146:45)
    at TransformOperationExecutor.transform (/home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:169:17)
    at /home/yan/Workspace/typex/node_modules/class-transformer/TransformOperationExecutor.js:26:41
    at Array.forEach (native)

Is this bug or am i doing something wrong.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 2
  • Comments: 16 (9 by maintainers)

Most upvoted comments

I was having the same issue while working with Mongoose documents (don’t even try without the .lean() option (or .toObject() when not a query), otherwise expect spectacular crashes).

Investigating a bit further, I found that even leaned objects have an _id property for which Object.keys returns [ '_bsontype', 'id' ], which causes the above error when class-transformer loops over those keys.

My curent solution is to assign doc.id = doc._id and then delete doc._id. Also make sure to have _id disabled for all your subdocuments, otherwise the same problem will occur.

I am using this: @Type(() => String)

No that’s not a requirment, they are like they are now. Thanks.

It would be great if you could look into the generic solution. But please open a new issue for that then