1

I am getting an error while using $regex in mongoose aggregation query . I am getting an invalid operator with error no 15999 . Please help guys.

{ $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
             }
  }
3
  • you can consider req.query.text as string Commented Jul 10, 2016 at 6:23
  • If you can use JS code, try escaping it as req.query.text.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'). If the text contains [ or ( or other special regex metacharacters, this should fix the issue. Commented Jul 10, 2016 at 11:17
  • Not sure if you can use regex in $project stackoverflow.com/questions/29866336/… Commented Jul 10, 2016 at 15:31

2 Answers 2

1

You can use regex in $match and you will get your result as in this example

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
})
}
})
Sign up to request clarification or add additional context in comments.

Comments

0

Doing just agg.match({'<fieldName'>:new RegExp('^' + req.query.district, "i")}) didnt work for me

I had to use eval in the solution. if you are JSON.stringifying the aggregate query to see the output you won't see the effect of eval. Eval will have an effect later on when passed down to mongo.

agg.match({'<fieldName'>:eval(new RegExp('^' + req.query.district, "i"))});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.