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
Just construct the condition dynamically, you’re already doing most of the work:
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:
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.