Skip to content

Instantly share code, notes, and snippets.

@ianfabs
Created March 2, 2019 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianfabs/30959d1390a2fc43f425f2047ad125e9 to your computer and use it in GitHub Desktop.
Save ianfabs/30959d1390a2fc43f425f2047ad125e9 to your computer and use it in GitHub Desktop.
This function solves an issue i was experiencing on a project where mongoose wasn't correctly returning an object for graphql resolvers. This fixes that issue by returning a new version of the object supplied to the function and converting the object id to a string.
//long version
const objectify = object => (
object.isArray()
?
object.map(element => objectify(element))
:
({
...object.toObject(),
_id: object._id.toString(),
})
);
//Short, better version
const objectify = o => (o.isArray()?o.map(e => objectify(e)):({...o.toObject(),_id:o._id.toString()}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment