2016-11-21 94 views
0

我想在使用MongoDB的Node JS中的項目中創建高級搜索。我在數據庫中創建了一個搜索關鍵字段。用戶可以在文本框中輸入任何單詞,並且我希望在字符串中匹配並獲取結果。低於我的數據庫結構和代碼。我的代碼工作只匹配所有字符串中不搜索的字符串的第一個字。在節點js中搜索字符串mongodb中的任何詞

DB : 
{ 
"_id": ObjectId("001"), 
"searchkey": "Test Product Test Product T-shirt Half sleeves Adidas" 
} 
{ 
"_id": ObjectId("123"), 
"searchkey": "boy test Product Test Product T-shirt Half sleeves Nike" 
} 
{ 
"_id": ObjectId("456"), 
"searchkey": "girl test Product Summer Product T-shirt full sleeves Adidas" 
} 
{ 
"_id": ObjectId("789"), 
"searchkey": "any product any Product any Product T-shirt full sleeves Adidas" 
} 
{ 
"_id": ObjectId("1010"), 
"searchkey": "woodland Product woodland Product T-shirt Half sleeves woodland" 
} 
{ 
"_id": ObjectId("1212"), 
"searchkey": "Summer Product Test Product T-shirt Half sleeves Adidas" 
} 

My Query : 

Collection.find({searchkey : {$regex: new RegExp('^' + search.toLowerCase(), 'i')},searchkey : {$regex: new RegExp('^' + search.toUpperCase(), 'i')},is_active:true},function(error,fetchSearch){ 
console.log(fetchSearch); 
}); 

如果我搜索test or TEST它會給我只有一個結果是id爲001,結果沒有從所有的字符串相匹配的休息。

我要像如果我搜索summerSummer它會給我456 and 1212 _id數據。

回答

2

您只是檢查字符串是否以用戶的搜索字符串開頭。

^ =表示字符串的開始,所以'^' + search.toLowerCase()意味着搜索被開始search.toLowerCase()一個字符串,僅此而已。如果它不會以搜索字符串開始 - 它不會匹配。這就是爲什麼test只有id 001獲得一場比賽。

將您的搜索模式更改爲:'.*' + search.toLowerCase() + '.*'可在字符串內的任意位置查找搜索字符串。

Here is the new regex,你可以看到它是匹配的 '夏季' 既456和1212

+0

現在意味着我的查詢像下面 –

+1

Collection.find({searchkey {$ regex:new RegExp('。*'+ search.toLowerCase()+'。*','i')},searchkey:{$ regex:new RegExp('。*'+ search.toUpperCase()+ '。*','i')},is_active:true},function(error,fetchSearch){console.log(fetchSearch); }); –

+0

謝謝先生(弓) –

1

更改您的查詢是這樣的:

db.getCollection('Stackoverflow').find({ searchkey: {$regex: "test", $options: "$i"}})