2013-04-15 111 views
8

我試圖從用戶搜索的內容中產生一個查詢。我有我只是想通過在MongoDB中選擇要發送的字符串數組,我的問題是與/文字/語法,它完美的作品從MongoDB的控制檯是這樣的:Meteor&mongoDB LIKE查詢

Items.find({ $or: [{name: /doc/}, {tags: /doc/}, {name: /test/}, {tags: /test/}] }); 

但我不能設法在JavaScript中寫同樣的語法,我試過幾個版本。

var mongoDbArr = []; 
    searchArray.forEach(function(text) { 
    mongoDbArr.push({name: /text/}); 
    mongoDbArr.push({tags: /text/}); 
    }); 
    return Items.find({ $or: mongoDbArr}); 

但它只搜索「文本」,而不是變量中的內容。像這樣:

但是,這並沒有給我任何結果。我錯過了什麼?

+0

你在服務器上使用mongodb還是在客戶端使用minimongo? (或兩者?) – mquandalle

+0

現在,兩者。我只是想與流星默認設置的應用程序。 – Snidd

回答

18

你必須用JavaScript來建立你的正則表達式:

var mongoDbArr = []; 
searchArray.forEach(function(text) { 
    mongoDbArr.push({name: new RegExp(text)}); 
    mongoDbArr.push({tags: new RegExp(text,"i")}); 
}); 

return Items.find({ $or: mongoDbArr}); 

或者使用regular expressions查詢與MongoDB的:

mongoDbArr.push({name: { $regex : text, $options:"i" } }); 
mongoDbArr.push({tags: { $regex : text, $options:"i" } }); 

爲了逃避特殊字符,您可以在使用之前做到這一點text(來自JQuery UI的源代碼)

text = text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); 
+0

正則表達式現在工作,即時通訊擔心當用戶輸入保留字符,這意味着在正則表達式中不同的事情會發生什麼。 – Snidd

+0

我修改了答案以逃避特殊字符。 – Akshat

+0

哇。這兩個正則表達式查詢都在客戶端工作嗎?哇。是的,它確實。頭腦風暴。把它放在我的新[流星自動完成](https://github.com/mizzao/meteor-autocomplete)包中... –

5

在發佈功能在服務器試試這個:

return YourCollection.find({'$or' : [ 
    { 'field1':{'$regex':searchString} }, 
    { 'field2':{'$regex':searchString} }, 
    { 'field3':{'$regex':searchString} }, ] 
}); 
+0

這一個爲我工作。謝謝! –