Created
November 30, 2011 09:19
-
-
Save tdegrunt/1408494 to your computer and use it in GitHub Desktop.
traverse-js example
This file contains hidden or 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
var Connection, Db, Server, build, exec, fixtures, fs, print, spawn, _ref, _ref2; | |
_ref2 = require('mongodb'), Db = _ref2.Db, Connection = _ref2.Connection, Server = _ref2.Server; | |
_ = require('underscore'); | |
util = require('util'); | |
traverse = require('traverse'); | |
var the_db = new Db('geowars', new Server("localhost", 27017, {})); | |
var translations = { | |
"equippableitemtypes": [ "skillType", "cost.chronolite" ], | |
"collectiontypes": ["items"], | |
"users": [ | |
/collections.[0-9]*.collectionType/, | |
/collections.[0-9]*.completedItems.[0-9]*/ | |
] | |
}; | |
/** @ignore */ | |
var get = function (obj, path) { | |
var segments = path.split('.') | |
, cursor = obj | |
, segment, i; | |
for (i = 0; i < segments.length - 1; ++i) { | |
segment = segments[i]; | |
cursor = cursor[segment] = cursor[segment] || {}; | |
} | |
return cursor[segments[i]]; | |
}; | |
var set = function (obj, path, value) { | |
var segments = path.split('.') | |
, cursor = obj | |
, segment, i; | |
for (i = 0; i < segments.length - 1; ++i) { | |
segment = segments[i]; | |
cursor = cursor[segment] = cursor[segment] || {}; | |
} | |
cursor[segments[i]] = value; | |
}; | |
var TYPE = "users"; | |
the_db.open(function(err, db) { | |
db.collection(TYPE, function(err, collection) { | |
collection.find({}, function(err, cursor) { | |
cursor.toArray(function(err, items) { | |
var result = {}; | |
_.each(items, function (item) { | |
result[item._id] = traverse(item).map(function(x){ | |
var self = this; | |
var path = self.path.join('.'); | |
_.each(translations[TYPE], function(translationItem) { | |
if( _.isString(translationItem) && path === translationItem || | |
_.isRegExp(translationItem) && path.match(translationItem)) { | |
self.update("#REF!"+x); | |
} | |
}) | |
}); | |
delete result[item._id]._id; | |
}); | |
console.log(util.inspect(JSON.parse(JSON.stringify(result)), false, null, false)); | |
db.close(); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment