Convert ID Properties Back to BSON from JSON

Recently, I started using Backbone with MongoDB to build an app. As I started integrating an “edit” feature I ran into a rather vexing problem: my $oid fields kept getting converted to strings whenever I updated a document. This caused all manor of havoc with my queries: Data wasn’t getting returned properly, results sets were empty, pages crashed because of null values, etc. Unfortunately, after doing a bunch of research, the best advice I found related to modifying toJSON and parse methods to convert ID fields back to their original values when posting. This really wasn’t an option for me since I had a number of nested documents in my data structure that also had $oid fields that needed to be converted. For example:

..
"workHistory" : [{
    "description" : "",
    "endDate" : null,
    "name" : "SomeCompany",
    "skills" : [{
        "_id" : ObjectId("549b29c970b452eeb6acecd4"),
        "name" : "CSS",
        "description" : ""
    }]
}]

I needed a way to check a document for potentional $oid fields and convert them back to their correct BSON values. Here’s what I came up with:

var parseIds = function(obj) {
    var objProperties;

    objProperties = Object.keys(obj);
    if (_.isObject(obj) === true) {
        objProperties.map(function(value, index, list) {
            if (value.charAt(0) === "_") {
                obj[value] = mongo.helper.toObjectID(obj[value]);
            } else if (_.isObject(obj[value]) === true) {
                parseIds(obj[value]);
            }
        });
    }

};

In the parseIds function, we’re looping through all the properties of the passed in object and looking any property whose name started with an underscore (this is an arbitrary naming convention for ID fields that I came up with). If it finds one, it converts the value and updates the object in place.

Hopefully, someone else finds this useful. If anybody knows of a better way to handle this, please let me know in the comments.