0

I am accepting a user-supplied JSON string that looks like MongoDB query and I want to do some validation and processing on it and issue it to MongoDB as a query.

  1. I'm using MongoSkin driver for node.js
  2. the query string might have an _id field, and it may be embedded in a sub-doc.
  3. it can have a date or dates (which in this case is a timedate, like "2013-11-05T15:29:32.128Z"). Here I don't have control over the property names so the key might be "createdOn", "lastUpdated", "submitted", etc.

Currently, I am doing the below but it's behaving strangely. For nested keys (like "parent._id", the object I pass to collection.find() looks like {'parent_.id':'xyz'}, for a root key, like "_id", the object I pass to find() looks like {_id:'xyz'}

  1. Use JSON.parse to parse the query string into an object
  2. pass that object into two recursive functions, one for the ids, one for the dates (example below)
  3. Use the resulting object as the query parameter for collection.find()

The query strings can look something like the following but I don't have control over them.

{"_id":"12o3iu4y2134iouy", "submitted":"2013-11-05T15:29:32.128Z"}

{"child._id":"12o3iu4y2134iouy", "comment.submitted":"2013-11-05T15:29:32.128Z"}

Any suggestions on the approach, or something wrong with my function/algorithm>?

function recurseForMongoKeys(qString){
    for (key in qString) {
        if (typeof qString[key] === 'object'){
            recurseForMongoKeys(qString[key]);
        }
        else {
            if (key.split(".").pop() === '_id') {  // process leaf node
            key = req.coll.id(qString[key]);
        }
    }
}

update: I just discovered that my nested id ("child._id" in the example above) is not actually an ObjectId but just a 24-digit Hex string that I used from the child doc's ObjectId.

rogodeter
  • 460
  • 9
  • 19
  • Am I reading this right in thinking it does not work when the data has just "_id" but does work when it has "child._id"? – SamA Nov 05 '13 at 18:37
  • SamA -- Yes, that is correct, but based on my recent update I think (still investigating) that makes sense, as the child._id is NOT an ObjectId but a hex string... Looks like my recursive function is NOT doing what I think it is, which explains why it works for child._id and not for _id. Need to figure out why the recursive function isn't replacing the element properly. – rogodeter Nov 05 '13 at 19:15

0 Answers0