I have mongoose Find code function , the query is recieved from params (Here currently hardcoded) Suppose this as the query
var arrayOfCategories = [ '63073212ed3e0f85ccffc8cf' , '63073324ed3e0f85ccffc8ff']
var arrayOfSkill = []
This is my find code
const astro =await Astrologer.find({ 'category.astolCat_id' : {$in: arrayOfCategories},
'skills.astolSkill_id': { $in: arrayOfSkill}})
It works fine if I have a value in 'arrayOfSkill' array but I want it to ignore ''skills.astolSkill_id': { $in: arrayOfSkill}' and only query for arrayOfCategories if arrayOfSkill is blank. If arrayOfSkill is blank then I is returning blank array
CodePudding user response:
Build up your query options progressively...
const query = {};
if (arrayOfCategories.length) {
query["category.astolCat_id"] = { $in: arrayOfCategories };
}
if (arrayOfSkill.length) {
query["skills.astolSkill_id"] = { $in: arrayOfSkill };
}
const astro =await Astrologer.find(query);