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.
- I'm using MongoSkin driver for node.js
- the query string might have an _id field, and it may be embedded in a sub-doc.
- 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'}
- Use JSON.parse to parse the query string into an object
- pass that object into two recursive functions, one for the ids, one for the dates (example below)
- 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.