2016-12-01 41 views
0

的NodeJS怎麼辦包含在搜索的NodeJS和MongoDB

search_key = new RegExp('.*' + req.params.search_key + '.*', 'i'); 
Item.find({product_name:search_key}).exec(function (err, items) { 
    console.log(items)); 
}); 

我可以在這裏搜索產品名稱與SEARCH_KEY。但是我的問題是,我的產品名稱是「COMPLAN MILK BISCUITS 100GM」。如果我使用「BISCUITS COMPLAN」進行搜索,則不會找到該產品。我需要根據搜索中的包含找到「BISCUITS COMPLAN」和「COMPLAN BISCUITS」。

+0

不complitly肯定與你的要求。你想要「BISCUITS COMPLAN」找到所有含有BISCUITS或COMPLAN的產品嗎?或者兩者都沒有特定的順序? –

+0

您是否嘗試過如下解決方案:[http://stackoverflow.com/questions/3305561/how-do-i-query-mongodb-with-like](http://stackoverflow.com/questions/3305561/how- do-i-query-mongodb-like-like) – mcatta

+0

@SimonPA我有一個產品名稱complan牛奶餅乾100gm.If項目與關鍵字Complan搜索,它獲取該項目。但是,如果我用餅乾Complan搜索,它沒有找到該項目。我需要找到該項目如果我們使用關鍵字Biscuits Complan進行搜索。 – Nivin

回答

2

您需要創建文本索引來實現您的目標,然後從文本索引字段進行搜索。蒙戈shell命令來創建text indexproduct_name

db.colectionName.createIndex({ product_name: "text" }); 

那麼你可以使用$text$search搜索。 doc

db.collectionName.find({ $text: { $search: "BISCUITS COMPLAN" } }); 

沒有必要使用new RegExp(正好可以利用這樣的:

Item.find({ $text: { $search: req.params.search_key } }).exec(function (err, items) { 
    console.log(items)); 
});; 
0

您需要使用$text運算符。

所以不是:

Item.find({product_name: search_key})... 

喜歡的東西:

Item.find({product_name: {$text: {$search: search_key}}})... 

注意:您需要有一個text index