Let say I have dynamic array
const branddata = ["adidas", "nike", "puma"]
//this data can be sometime empty too like
// const branddata = []
//now I want to search all the product with brands like
const product = productmodel.find({brand:branddata})
The problem is, this thing works when branddata array is not empty and it gives me the product.
But when it is empty the find method search for a brand which is equal to "" and gives me zero product.
I want all the products to be displayed if branddata is empty.
How can I get this using $regex or any other?
2
Answers
Finally found a solution with a function-based approach
$in is used to find document data which are in the array and $nin is used to find document data which are not in the array (basically when array is empty)
you can check branddata is empty or not, and create query object based on it, like this
when you have multiple params,you can do something like this