Last active
July 28, 2021 06:27
-
-
Save fsfarah/390c49b8096e1ffdc67b7ca76f87be06 to your computer and use it in GitHub Desktop.
Stringify ObjectID in JSON.stringify when running js in MongoDB terminal
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
// 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