realm-js icon indicating copy to clipboard operation
realm-js copied to clipboard

Feature suggestion: first() to fetch first available object

Open bosung90 opened this issue 9 years ago • 1 comments

A lot of times, when I query realm, I only expect a single object ( for example filtering by a primary key) However, because query always returns Ream.Results (Which is array), I first need to check if the length is greater than 0 before trying to access the first item (or it will throw exception).

So instead of doing

const dogs = realm.objects('dog').filtered('id == 123')
if(dogs.length > 0){
   return dogs[0]
}
return null

I propose first() which simply returns first Realm.Object or returns null

return realm.objects('dog').filtered('id == 123').first()

Furthermore, I would also recommend last() and get(index: int)

last() equivalent will be as follows

const dogs = realm.objects('dog').filtered('id == 123').slice(-1)
if(dogs.length >0){
   return dogs[0]
}
return null

// or

return realm.objects('dog').filtered('id == 123').last()

get(2) equivalent will be as follows

const dogs = realm.objects('dog').filtered('id == 123')
if(dogs.length > 2){
   return dogs[2]
}
return null

// or

return realm.objects('dog').filtered('id == 123').get(2)

bosung90 avatar Oct 29 '16 07:10 bosung90

Normally you would want a wrapper for realm so I'm adding those shorthands to my wrapper class like get(), first(), etc. I loop through all my schema classes and inject these useful functions.

lodev09 avatar Feb 22 '17 16:02 lodev09