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

MongoDB filter list by number or string

This is one doc in my "Assets" collection.

{
  ...
  category: "categoryName"
  name: "assetName",
  weight: 400,
  ...
}

I need to filter by "name" or "weight" and this is what I do in NodeJS

...(filter) && {
  $or: [
    { name:     { "$regex": filter, "$options": "i" } }
    { weight:   +filter                               } // filter is string
  ]
}

I get the following error because weight in my model is of type Number and I don’t want to change that.
CastError: Cast to Number failed for value "NaN" (type number) at path "weight"

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

what would be the best way to handle this?

>Solution :

Just construct the condition dynamically, you’re already doing most of the work:

...(filter) && {
    $or: [
        { name:     { "$regex": filter, "$options": "i" } }
        // some condition that will always return false when is filter is NaN
        ( isNaN(filter) ? { name: "Does not exist" } : { weight:   +filter }) 
    ]
}
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