Skip to content

Instantly share code, notes, and snippets.

@saggiyogesh
Last active April 25, 2018 10:58
Show Gist options
  • Save saggiyogesh/386493110ec6479579b501e55c4b1716 to your computer and use it in GitHub Desktop.
Save saggiyogesh/386493110ec6479579b501e55c4b1716 to your computer and use it in GitHub Desktop.
Parsing custom objects in JSON.parse in javascript
// This script is executed in mongo shell to replace all occurence of a STRING, with an objectId string
// and then using parse, converting objectId string to actual objectId
db.Dummy.find({}).forEach(function(doc) {
console.log(doc._id);
let newDoc = JSON.stringify(doc).replace('STRING', '5ab23ff3423159ad5d0251c0');
print('newDoc', newDoc);
let jsonDoc = JSON.parse(newDoc, (key, value) => {
if (value === '5ab23ff3423159ad5d0251c0') {
return ObjectId(value);
} else {
return value;
}
});
print(jsonDoc);
delete jsonDoc._id;
db.Dummy.findOneAndUpdate(
{ _id: doc._id },
{
$set: jsonDoc
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment