How to compare int as string?

Viewed 61

I'm using Realm in my React Native app.
There is a search bar to filter data by ID, and that ID is int in my database.

If user searches for 418, I need to return all IDs like 41878, 41835.

Here is some code:

findAll({ search }) {
  let items = this._realm.objects<Data>(this._schema.name)

  if (search.length)
    items = items.filtered(`id = '${search}'`)

  return items
}

As expected, this code only returns the item that have the exact ID 418.

I tried something like

items.filtered(`id CONTAINS '${search}'`)

But gives me:
Error: Unsupported comparison operator 'contains' against type 'int', right side must be a string or binary type

I can't use Array's filter because it will make the Realm execute the query and slow down the code.

How can I achieve this without triggering the Realm to run the query?

1 Answers

CONTAINS is not supported on Int types.

There are a few solutions:

One is to keep two properties in your model, one an Int and one a String version of that Int. You could implement that pretty easily through an init function within the object that assigns the Int and then makes a string version for the string property

Another is to store all of the values as Strings. You'll just need to Int them if sorting or doing calculations. You can then use CONTAINS

Related