2013-02-11 46 views
0

我在頁面中實現了一個標籤系統。當用戶輸入任何字符串時,它將觸發我的快速路由並嘗試查找輸入的內容以填充列表並將其作爲JSON返回以處理回調。問題是關於moongose,因爲查詢是非常正確的,並且如果我在mongo shell上執行它就可以正常工作。Mongoose查找查詢不起作用,即使等效查詢在mongodb上也能正常工作

查詢:

var token = '/.*' + req.query.search + '.*/i'; 
Tag.find({ description: token , inactivatedAt: null }, function(err, tags) { 
    var tempArray = []; 

    if (tags) { 
     var counter = 0; 

     tags.forEach(function(tag) { 
      var dArray = []; 

      dArray.push(counter++); 
      dArray.push(tag.description); 
      dArray.push(null); 
      dArray.push(null); 
      tempArray.push(dArray); 
     }); 
    } 

    res.writeHead(200, {'content-type': 'text/json'}); 
    res.end(JSON.stringify(tempArray)); 
}); 

即使我查詢爲description: { $regex: token }description: token結果沒有找到。相同的查詢參數很好,並在shell上帶來了mongo的結果。例如:db.tags.find({ description: /.*MET.*/i , inactivatedAt: null }).pretty()但我的貓鼬查詢不起作用。

任何線索都會非常有幫助。提前致謝!

回答

1

您需要token轉換成正規快件,而不是隻是一個字符串的:

var token = new RegExp(req.query.search, 'i'); 
+1

另外請注意,任何特殊字符需要進行轉義使用新的RegExp'/富\ d /'或'新的正則表達式時('foo \\ d')' – Noah 2013-02-11 03:27:58

+0

爲我工作!多謝你們! – Ito 2013-02-11 03:42:30