Z-Car

How to escape Mongo keys using Node.js in a Flash

Dale is Flash Gordon's constant companion in his adventures, as well as his one true love.

Dale is Flash Gordon’s constant companion in his adventures, as well as his one true love.

Don’t be scared, dealing with Mongo is not that difficult, especially with some help from Flash.   While some people know of Mongo as a fictional planet where the comic  and movie serials of Flash Gordon takes place, ruled by a tyrant named Ming the Merciless, who governs with an iron hand, others are familiar with Mongo as a cross-platform document-oriented database system.

Many first-time users of  Mongo quickly find out that it does not allow insertion of keys with a dot (.) or dollar sign ($).  While understandable, this would seem to defeat the purpose of having a free-form document that is not rigidly defined.   Luckily, there is an easy way to address this issue in Node.js.  Below is a simple code snippet that I wrote which will escape the dot (.) or dollar sign ($) in any of your keys.

Just pass the document into the function, and your object will be escaped.  The dot (.) will be replaced with _dot_ and the ampersand (&) will be replaced with _amp_.  If required, you can change these to whatever you need.  If you need to unescape, you can easily swap the key.replace params.  I will leave this as an exercise to be completed by the reader…

function escapeKeys(obj) {
    if (!(Boolean(obj) && typeof obj == 'object'
      && Object.keys(obj).length > 0)) {
        return false;
    }
    Object.keys(obj).forEach(function(key) {
        if (typeof(obj[key]) == 'object') {
            escapeKeys(obj[key]);
        } else {
            if (key.indexOf('.') !== -1) {
                var newkey = key.replace(/\./g, '_dot_');
                obj[newkey] = obj[key];
                delete obj[key];
            }
            if (key.indexOf('$') !== -1) {
                var newkey = key.replace(/\$/g, '_amp_');
                obj[newkey] = obj[key];
                delete obj[key];
            }

        }
    });
    return true;
}
Syk is ruled by the witch-queen Azura, who is feared by everyone on Mongo.

Syk is ruled by the witch-queen Azura, who is feared by everyone on Mongo.

MongoDB is an open-source document database, and the leading NoSQL database.

MongoDB is an open-source document database, and the leading NoSQL database.

 

Leave a Reply and Let me know what you think...