1

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 2

1

you can check branddata is empty or not, and create query object based on it, like this

let q=(branddata && branddata.length>0 )?{brand:branddata}:{};
const product = productmodel.find(q);

when you have multiple params,you can do something like this

let params={
"brand":branddata,
"price":pricedata,
"gender":genderdata
}
let q={};
Object.Keys(params).forEach((t)=>{
if(params[t] && params[t].length>0 ){
    q[t]=params[t]
}
})
const product = productmodel.find(q);
Sign up to request clarification or add additional context in comments.

7 Comments

branddata ? - this won't check if array is empty. You probably meant branddata.length ?
Yeah, I got the point. This will work, but what if I have multiple set of array to be check like pricedata=[ ] based upon the fact that users can sometimes make the price filter sometimes don't,
Doing this again with all data is not convenient
can you give me list of all params like branddata=>brand,pricedata=>price
branddata, pricedata, genderdata=>gender all the array can be empty sometime
|
0

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)

const branddata = ["adidas", "nike", "puma"]
const pricedata =["100"]
const genderdata =["male","female"]

const queryfunc = (value)=>{
        var q = {}
        if(value==''){
            q["$nin"]=value;
        }
        else{
            q["$in"]=key;
        }
        return q
 }
 
 const brand=queryfunc(branddata)
 const price=queryfunc(pricedata)
 const gender=queryfunc(genderdata)
    
const product = productmodel.find({brand,price,gender})

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.