I'm porting a webserver from python to node.js and one of the capabilities that server must have is to receive a POST containing information about a MongoDB query, and send the result of the query to the webpage. The query may or may not contain a filter, a projection, a limit and a sort. In python we can do it like this:
(In the examples below command_name equals to 'find')
command = getattr(collection, command_name)
cmd_filter = loads(filter_str) if filter_str else None
projection = loads(projection_str) if projection_str else None
limit = loads(limit_str) if limit_str else 0
sort = [(elt['key'], elt['order']) for elt in loads(sort_str)] if sort_str else None
response = command(filter=cmd_filter, projection=projection, sort=sort, limit=limit)
But I'm having trouble finding a way to do it in node.js, I've tried stuff like this:
command_name = req.body['command']
command = collection[command_name]
command = filter_str != undefined ? collection[command_name](JSON.parse(filter_str)) : collection[command_name]
command = projection_str != undefined ? command['project'](JSON.parse(projection_str)) : command
command = sort_str != undefined ? command['sort'](JSON.parse(sort_str)) : command
command = limit_str != undefined ? command['limit'](JSON.parse(limit_str)) : command
response = command.toArray(function(err, result) {
if (err) throw err
console.log(result)
})
But it doesn't work
via Ricardo Atanazio S Carvalho
No comments:
Post a Comment