Last active
December 2, 2018 13:57
-
-
Save barisere/e0368f42ac84cb3ff14c96a7cc255c61 to your computer and use it in GitHub Desktop.
Transform a Mongoose Document object's ObjectId fields to strings. This transformation is necessary, in order to use class-transformer's plainToClass function on documents with ObjectId fields. class-transformer fails and throws an error when converting the BSON ObjectId type to a Buffer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function extractMongoId(document) { | |
const doc = document.toObject ? document.toObject() : document; | |
for (const [key, value] of Object.entries(doc)) { | |
if (value instanceof ObjectID) { | |
delete doc[key]; | |
doc[key] = value.toHexString(); | |
} else if (value instanceof Object) { | |
doc[key] = extractMongoId(value); | |
} | |
if (Array.isArray(value)) { | |
doc[key] = value.map(extractMongoId); | |
} | |
} | |
return doc; | |
} | |
// Usage | |
plainToClass(targetType, Array.isArray(document) ? document.map(extractMongoId) : extractMongoId(document), transformOptions); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment