Mongoose Find() – Return all docs if query is undefined

Issue

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

Solution

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

Answered By – Phil

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published