2014-09-03 56 views
0

我有這個文件:查找文件找對象內

{ 
    "_id": ObjectId("xxx"), 
    "props": { 
    "a": "a1", 
    "b": "b2" 
    } 
} 

我的查詢看起來是這樣的:

db.collection.find({"$and": [ {"props.a" : "a1"}, {"props.b": "b2"} ]} 

我得到查詢的元素從GET值:

/api/search?a=a1&b=b1 

所以,我需要一種方法來產生我的查詢從GET對象開始dinamiically ...

我想過這樣的事情:

// Little helper to get the object key name by index 
Object.prototype.key = function key(int) { var j = -1; for(var i in this) { j++; if(j==int) { return i; } else { continue; } } } 

// My attempt 
var query = [], 
    i  = 0; 

_.each(req.query, function(prop) { 

    var key = req.query.key(i); 

    query.push({"props." + key: prop}); 

    i = i + 1; 

}); 

但它不工作...

如果我這樣做:

_.each(req.query, function(prop) { 

    var key = {}; 
    key.properties = {}; 
    key.properties[req.query.key(i)] = prop ; 
    props.push(key); 
    i = i + 1; 

}); 

我得到這個:

[{ props: { a: 'a1' } }, { props: { b: 'b1' } } ] 

但通過這種方式我只能得到這個查詢:

db.collection.find({"$and": [ { props: { a: 'a1' } }, { props: { b: 'b1' } } ]} 

這是從我上面(這一個搜索的道具是完全一樣,其包含的值之一,我所提供的那些,而不是原來的容貌一)

寫在一個完全不同的

我該怎麼辦?

+0

您是否正在使用任何HTTP庫或框架,如[http](http://nodejs.org/api/http.html)或[Express.js](http://expressjs.com/)?通常情況下,您會使用它來等待來自客戶端的「請求」,然後您可以獲取參數並以「響應」形式發回正確的數據。 – 2014-09-03 08:20:02

+0

是的,我使用快遞,但我的問題是如何生成查詢,而不是如何獲取或發送數據 – 2014-09-03 08:21:30

+0

這有幫助嗎? http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find – 2014-09-03 08:26:48

回答

0

好,我找到一個解決方案,在谷歌搜索沒有返回的任何解決方案...

var query = {"$and": []}, 
     props = [], 
     i  = 0; 

_.each(req.query, function(prop) { 

    var key = {}; 
    key["properties." + req.query.key(i)] = prop ; 
    props.push(key); 
    i = i + 1; 

}); 

query.$and = props; 

這樣生成的查詢酷似我需要它。