0
我將一個web服務器從python移植到node.js,服務器必須具備的一項功能是接收包含有關MongoDB查詢的信息的POST,並將結果查詢到網頁。該查詢可能包含或不包含過濾器,投影,限制和排序。在蟒蛇,我們可以像這樣做:如何在NodeJS中處理自定義MongoDB查詢
(在下面COMMAND_NAME的例子等於「找到」)
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)
但我無法找到一種方法做它的node.js,我已經嘗試過這樣的東西:
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)
})
但它不起作用。我得到一個MongoError: Can't canonicalize query: BadValue bad order array [2]
謝謝您的回答。我忘了在帖子中提到這是該公司的內部申請。如果有人惡意使用這個應用程序,我們可以很容易地找到它們,或者我們遇到的問題比有人搞亂這個數據庫。 –