Skip to content

Instantly share code, notes, and snippets.

@rajiteh
Created February 19, 2016 01:43
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 rajiteh/b092528d670e865a4884 to your computer and use it in GitHub Desktop.
Save rajiteh/b092528d670e865a4884 to your computer and use it in GitHub Desktop.
Traverses a defined set of collections and replaces a nested value in the document. Nested arrays handled automatically. (mongodb js)
/*
Traverses a defined set of collections and replaces a nested value in the document. Nested arrays handled automatically.
Author: @rajiteh
Usage:
var searches =
{
'collection_name': [
[ 'key', 'sub_key', 'sub_sub_key', ... ], // Path to target value.
...
]
}
mongoDeepReplace('toFind','toReplace', searches)
*/
var mongoDeepReplace = function(find, replace, searches) {
var DEBUG = false;
var debugPath = [];
var isDirty = false;
var printMsg = function() {
var timestamp = new Date().toISOString();
var args = Array.prototype.slice.call(arguments);
args.unshift(timestamp);
print.apply(null , args);
};
var escapeRegExp = function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
Object.keys(searches).forEach(function(collectionName) {
var collection = db[collectionName];
var searchPaths = searches[collectionName];
collection.find().forEach( function(doc) {
searchPaths.forEach(function (path) {
debugPath = [collectionName];
var recursiveReplace = function(items, path, find, replace) {
var isDirty = false;
var key = path.shift();
var itemValue = items[key];
debugPath.push(key);
if (itemValue == null || itemValue == undefined) {
if (DEBUG) {
printMsg("Path Error ===>", doc._id, JSON.stringify(debugPath));
}
} else {
if (itemValue instanceof String || typeof itemValue === 'string') {
if (itemValue.indexOf(find) > -1) {
items[key] = itemValue.replace(new RegExp(escapeRegExp(find),"g"), replace);
isDirty = true;
if (DEBUG) {
printMsg("Replaced ===>", doc._id, JSON.stringify(debugPath));
}
};
} else if (itemValue instanceof Array) {
itemValue.forEach(function (item, idx) {
loopPath = path.slice();
loopPath.unshift(idx);
loopDebug = debugPath.slice();
isDirty = recursiveReplace(itemValue, loopPath, find, replace) || isDirty;
debugPath = loopDebug;
});
} else if(typeof itemValue === "object") {
isDirty = recursiveReplace(itemValue, path, find, replace) || isDirty;
} else {
if (DEBUG) {
printMsg("Key Error ===>", doc._id, JSON.stringify(debugPath));
}
}
}
debugPath.pop();
return isDirty;
}
isDirty = recursiveReplace(doc, path.slice(), find, replace) || isDirty;
});
if (isDirty) {
collection.save(doc);
printMsg("Updated ===>", doc._id, JSON.stringify([collectionName]));
isDirty = false; // Reset flag
};
});
});
};
searches = {
'job': [
['sites', 'url']
],
'company': [
['sites', 'url']
],
'job_board': [
['styles', 'footer_html'],
['jb_settings', 'url'],
]
'message': [
['body']
],
}
mongoDeepReplace('http://kekker', 'http://docker', searches)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment