2016-07-09 49 views
1

在貓鼬聚合查詢中使用$ regex時出現錯誤。我遇到錯誤號爲15999的無效操作員。請幫助傢伙。

{ $match: { "_id": ObjectId(req.headers.token) } }, { 
         $project: { 
          inventory: { 
           $filter: { 
            input: '$inventory', 
            as: 'inventory', 
            cond: {$or:[{"$$inventory.item":new RegExp('^'+req.query.text+'$', "i")},{"$$inventory.sku":new RegExp('^'+req.query.text+'$', "i")}]} 
           } 
          }, 
          _id: 0 
      } 
    } 
+0

可以考慮req.query.text作爲字符串 –

+0

如果你可以使用JS代碼,試圖逃脫它作爲'req.query.text.replace(/ [ - \/\\^$ * +?。()| [\] {}]/g,'\\ $&')'。如果文本包含'['或'('或其他特殊的正則表達式元字符,這應該解決這個問題。 –

+0

不知道你是否可以在$ project中使用正則表達式http://stackoverflow.com/questions/29866336/regex-within-項目MongoDB的聚集 – jpaljasma

回答

1

可以在$匹配使用正則表達式,你會得到你的結果如本例

Pincodes.aggregate([ 
{ "$match": { "district": new RegExp('^' + req.query.district, "i") } 
}, 
{ "$group": { "_id": "$district" } }]) 
.exec((err, data) => { 
if (err) { 
res.status(500).json({ 
data: err 
}) 
} 
else { 
res.status(200).json({ 
data: data 
}) 
} 
})