2016-06-08 80 views
1

如果我在數據庫中有一個資源,我知道我可以在我的快車應用程序中使用mongodb npm軟件包來過濾$gt,$lt等的某些內容以僅接收回這些值基於我期望的過濾器。如何在Express中使用比較運算符來過濾查詢字符串

我也知道如何結合使用req.querymongodb取回我的查詢字符串的結果時,他們等於的東西(網址:http://localhost:3000/fruit?type=apple,快速/ mongodb的:collection.find(req.query)...)。

我該如何使查詢字符串表示我只想要大於或小於某些值?如果我只是想「等於」,我只是將它作爲另一個查詢參數(http://localhost:3000/fruit?type=apple&price=1)傳入,但如果我想要所有價格低於1的水果,該怎麼辦?

+1

只是一個想法,但我不認爲你會想要做'collection.find(req.query)',除非你事先驗證'req.query'。你會暴露自己要求注入,有人可以很容易地通過你的'''collection.find({})'' – peteb

+0

@peteb感謝你的建議! – bobbyz

回答

0
var filter = {}; 
if(req.query.type) 
    filter.type = req.query.type; 
if(req.query.price) 
    filter.price = req.query.price; 

// you cannot know if the incoming 
// price is for gt or lt, so 

// add new query variable price_gt (price greater than) 
if(req.query.price_gt) { 
    filter.price = filter.price || {}; 
    filter.price.$gt = req.query.price_gt; 
} 

// add new query variable price_lt (price less than) 
if(req.query.price_lt) { 
    filter.price = filter.price || {}; 
    filter.price.$lt = req.query.price_lt; 
} 

collection.find(filter); 
+0

這並不回答如何最好地構造查詢字符串以通過比較運算符 – peteb

+0

@peteb更新的問題,現在有意義嗎? –

+0

它肯定更好地解決了這個問題 – peteb

相關問題