Firebase query endAt() except/exclude its key

Viewed 399
a
b
c
d
e

FirebaseRef.orderByKey().endAt('c').limitToLast(2) will return

b, c

I want to retreive except c, so a, b are what I want.

How can I do this?

3 Answers

If your endAt() query uses strings, it will compare lexicographically, so you'll need to subtract one charCode from the last character of the string. The following should work when searching for strings:

FirebaseRef.orderByKey().endAt(exclude('c')).limitToLast(2) will return


exclude(key){
    return key.substring(0, key.length - 1) + String.fromCharCode(key.charCodeAt(key.length - 1) - 1)
}

@godlerner's answer worked best for me however an edge case needs to be added because if you have a key that ends with a 0 it will replace the 0 with "/" which will cause the query to fail and throw an exception because firebase does not allow keys to contains "/"

This works better

exclude(key) {
  let unallowedChars = '.#$/[]'
  let newKey = key.substring(0, key.length - 1) + String.fromCharCode(key.charCodeAt(key.length - 1) - 1)

  if(unallowedChars.includes(newKey[newKey.length - 1])){
    while(unallowedChars.includes(newKey[newKey.length - 1])) {
      newKey = newKey.substring(0, newKey.length - 1) + String.fromCharCode(newKey.charCodeAt(newKey.length - 1) - 1)
    }
  }

  return newKey
}
Related