2017-07-07 65 views
1

我有一個貓鼬模型的查詢字符串的問題。下面的代碼工作正常。但是,如果我構建相同的查詢作爲一個字符串它不起作用。 「查詢」的控制檯輸出mongoose model.find查詢字符串

'diagnosis_text_de': /.*depression.*/i 

我不明白這是爲什麼不工作,如何解決這一問題。

工作:

getByFullText = (req, res) => { 
    let query: String = '\'diagnosis_text_de\': /.*' + req.body.qICD + '.*/i'; 
    console.log(query); 
    this.model.find({ 
     'diagnosis_text_de': /.*depression.*/i 
    }, (err, docs) => { 
     if (err) { 
      return console.error(err); 
     } 
     res.json(docs); 
    }); 
} 

不工作:

... 
this.model.find({ query }, (err, docs) 
... 
+0

不要使之成爲「串」。把它作爲一個「對象」來開始。 'let query = {'diagnosis_text_de':new RegExp('。*'+ req.body.qICD +'。*','i')}; this.model.find(query,(err,docs)=> {'。你不能也使用ES6簡寫爲'{query}',因爲這意味着「query」也是關鍵字的名字。代替施工對象形式 –

+0

謝謝!作品魅力無窮! –

回答

0

親愛的,你可以使用MongoDB的運營商正則表達式$ $和選項如下

getByFullText = (req, res) => { 
     let query = { 
      diagnosis_text_de:{ 
      $regex: req.body.qICD, 
      $options:"i" 
      } 
     } 
     this.model.find(query,(err, docs) => { 
      if (err) { 
       return console.error(err); 
      } 
      res.json(docs); 
     }); 
    }