I am currently working with MERN stack for an E-commerce website
I am finding a syntax in Mongoose like:
Product.find({ brands: {$in : ["Brand1", "brand2", "BRAND3"], $option: 'match all cases'}})
I expect the result will match all Products that have brand1 or Brand1 or BRAND1, Brand2 or brand2, and so on...
How can I solve it in Mongoose v6.0.13?
CodePudding user response:
If want to execute in mongoDB compass use below query
Product.find({brands :{$in:[new RegExp('brand1', 'i'), new RegExp('brand2', 'i')]}} )
If using mongoose use
Product.find({ brands:{$in:[{ $regex: new RegExp('brand1', "i") }, { $regex: new RegExp('brand2', "i") }] })
CodePudding user response:
You should pass brand name in quotes.
Product.find({ brands: {$in : ["Brand1", "brand2", "BRAND3"], $option: 'match all cases'}})
to make case insensitive search,
var brands = [/^Brand1$/i,/^brand2$/i,/^BRAND3$/i];
Product.find({ brands: {$in : brands}})
CodePudding user response:
I have found a solution:
let regex = brands.join("|"); Product.find({ brands: { $regex: regex, $options: 'i' });
Thank you everyone for helping