javascriptnode.jsmongodbmongoosemongoose-schema

MongoDB filter list by number or string


This is one document 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 Node.js:

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