Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading