Reputation: 3316
I am new to mongoose and nodejs. I am trying to query an array field of mongoose schema using regular expression but I am getting an empty array even if there are matching elements. This is how my code looks like:
var regex = { $regex: new RegExp(req.query.query, 'i')};
var query = {$or: [
{name: regex}
, {ditributionAreas: {$in: [regex]}}
]};
TiffinboxSupplier.find(query, function(err, tiffinBoxSuppliers) {
if(err) { return next(err); };
res.json(tiffinBoxSuppliers);
});
Code works fine for name
field but giving issues with distributionAreas
array. Am I doing some mistake with $in
operator? Any help will be greatly appreciated.
Upvotes: 0
Views: 1764
Reputation: 3316
I got it to working, I only had to pass
new RegExp(req.query.query, 'i')
as value to $in
operator instead of
{ $regex: new RegExp(req.query.query, 'i')}
.
Therefore, above code becomes
var regex = { $regex: new RegExp(req.query.query, 'i')};
var query = {$or: [
{name: regex}
, {ditributionAreas: {$in: [new RegExp(req.query.query, 'i')]}}
]};
Upvotes: 4