2016-10-20 18 views
0

我試圖找到我的服務器端蒙戈查詢,我的查詢是這樣的如何避免在蒙戈查詢雙引號的正則表達式

{ 
    $text: { $search: "beautiful" }, 
    "Category": { 
     $elemMatch: { 
      "title": { $in: [/Home/] } 
     } 
    }, 
    "Company": { $regex: /philips/i } 
} 

以上查詢,我得到確切結果我想,但我的問題是,公司名稱"philips"是從我的HTML頁面到服務器端,並在服務器端它試圖將其轉換爲這樣的/philips/i爲了在查詢中使用它,但它在mongo查詢中採用字符串。

我的嘗試:

var productCompany = philips; // <---(getting this from my html page)   
var productCmpnyRegex = '/' + productCompany + '/i'; 
query = { 
    $text: { $search: "beautiful" }, 
    "Category": { 
     $elemMatch: { 
      "title": { $in: [/Home/] } 
     } 
    }, 
    "Company": { $regex: productCmpnyRegex } 
} 

我期待什麼:

query = { 
    $text: { $search: "beautiful" }, 
    "Category": { 
     $elemMatch: { 
      "title": { $in: [/Home/] } 
     } 
    }, 
    "Company": { $regex: /philips/i } 
} 

但它以它爲

query = { 
    $text: { $search: "beautiful" }, 
    "Category": { 
     $elemMatch: { 
      "title": { $in: [/Home/] } 
     } 
    }, 
    "Company": { $regex: "/philips/i" } 
} 

回答

2

環繞你的正則表達式模式在RegExp構造函數,它創建一個正則表達式對象,用於將文本與模式進行匹配:

var productCmpnyRegex = new RegExp(philips, 'i'); // <-- creates a regex obj /philips/i; 
query = { 
    "$text": { "$search": "beautiful" }, 
    "Category": { 
     "$elemMatch": { 
      "title": { "$in": [/Home/] } 
     } 
    }, 
    "Company": productCmpnyRegex 
}