javascriptnode.jsmongodbmongoosemongoose-schema

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"

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