Skip to content

Instantly share code, notes, and snippets.

@fsfarah
Last active July 28, 2021 06:27
Show Gist options
  • Save fsfarah/390c49b8096e1ffdc67b7ca76f87be06 to your computer and use it in GitHub Desktop.
Save fsfarah/390c49b8096e1ffdc67b7ca76f87be06 to your computer and use it in GitHub Desktop.
Stringify ObjectID in JSON.stringify when running js in MongoDB terminal
// when running a js script directly from mongo terminal
// and want the output saved in a file
// JSON.stringify the query result will result in empty object {} for ObjectId
// use the following function as a replacer
function stringifyObjectId(key, value) {
if (value instanceof ObjectId) {
return value.str; // example result "6100f43d0e2d24b8c7cd58af"
}
return value;
}
// example
JSON.stringify(result, stringifyObjectId, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment