Last active
April 25, 2018 10:58
-
-
Save saggiyogesh/386493110ec6479579b501e55c4b1716 to your computer and use it in GitHub Desktop.
Parsing custom objects in JSON.parse in javascript
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
// 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