Home > Net >  mongodb find method to display all data if array is empty
mongodb find method to display all data if array is empty

Time:09-02

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?

CodePudding user response:

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);

CodePudding user response:

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})

  • Related