skip to Main Content

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?

2

Answers


  1. 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 }) 
        ]
    }
    
    Login or Signup to reply.
  2. To handle this issue, you can check whether the filter for "weight" is a valid number before applying it to the query. You can use the isNaN function to determine if the filter can be converted to a valid number. If it’s a valid number, include it in the query; otherwise, exclude it. Here’s an example modification to your existing code:

    const weightFilter = +filter; // Convert the filter to a number
    
    const query = {
      ...(filter) && {
        $or: [
          { name: { "$regex": filter, "$options": "i" } },
          !isNaN(weightFilter) && { weight: weightFilter }
        ].filter(Boolean) // Remove falsy values (null, undefined, etc.)
      }
    };
    
    // Use the 'query' object in your MongoDB query

    This way, you only include the weight filter in the query if it can be successfully converted to a number. The filter(Boolean) removes any falsy values from the array, ensuring that only valid filters are included in the $or array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search