Removing particular elements from an array using dynamic, mongo-like expressions

I am designing a light mongo-like database which takes an object-oriented query statement such that each periodically seperated reference may either be a function or object reference:

foo.users.find( args );
foo.users.remove( args );

Where args is a JSON encoded object string.

Each function my database supports must take a pointer to the current result set with which to operate on (given by obj) as well as a comparator object, similar to those seen in mongo.

remove:function(obj,comp){
    comp = JSON.parse(comp);
    var result = [];
    for(var i =obj.length-1;i>=0;--i){

        /**For each object in the array*/
        var match = true;
        for(var key in comp){
            /**For each comparator field*/

            for(var test in comp[key]){
                /**For each logical comparator test*/
                if(comparators[test](obj[i][key],comp[key]) == false){
                    /**A logical test failed, this item does not match
                    all the criteria*/
                    match=false;
                    break;
                }
            }

        }
        if(match == true){
            /**The item matches the given criteria*/
            result.push( obj.slice(i,i+1)[0] );
        }
    }
    return result;
}

In my specific use case, the query:

users.remove({"username":{"$eq":"Hello_World"}})

Did not work, even though other queries which operate on the same data set, in a similar manner, would work correctly. The 'users' reference points to a location on a tree which IS an array of objects and it DOES contain the appropriate user object.

Changes should be made permanent to the tree however, it is not currently working as such. A further query to the tree would reveal that the user "Hello_World" was never removed and is a valid user.

No changes are made to 'obj' outside similar functions. Also, the return should be an object-array with 1 object however, contains none.

Answers


I have found and solved the issues:

  1. My comparator test in the 3rd nested loop, should instead be:

    if (comparators[test](obj[i][key],comp[key][test]) == false){

}

  1. Instead of obj.slice(), try obj.splice(). Only logic I could see to this was that my NodeJS environment does not support the function (which I would usually think otherwise).

In the end, it works as directed, now onto bigger and better things


Need Your Help

SQL COMMAND returning empty result set for address

mysql sql database

I am trying to retrieve all employees whose address is in Houston,Texas from the a table called employee using the following command but i am getting an empty result. The tables have all the inform...