Skip to content

Instantly share code, notes, and snippets.

@barisere
Last active December 2, 2018 13:57
Show Gist options
  • Save barisere/e0368f42ac84cb3ff14c96a7cc255c61 to your computer and use it in GitHub Desktop.
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.
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