Firebase查询endAt()除了/排除其键

时间:2017-09-18 08:56:00

标签: firebase firebase-realtime-database

a
b
c
d
e

FirebaseRef.orderByKey().endAt('c').limitToLast(2)将返回

b, c

除了c之外我想要撤退,所以a, b就是我想要的。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

在这种情况下,您需要使用limitToFirst()方法,如下所示:

FirebaseRef.orderByKey().limitToFirst(2);

您输出的内容为:a, b

如果您在a之前有数据,则需要startAt()endAt这样的方法:

FirebaseRef.orderByKey().startAt('a').endAt('b');

请参阅有关Retrieving Data in Firebase

的官方文档

答案 1 :(得分:0)

如果您的endAt()查询使用字符串,它将按字典顺序进行比较,因此您需要从字符串的最后一个字符中减去一个charCode。搜索字符串时,以下内容应该有效:

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)
}

答案 2 :(得分:0)

@godlerner的答案对我来说最有效,但是需要添加一个边缘情况,因为如果您的键以0结尾,它将用“ /”替换0,这将导致查询失败并引发异常,因为firebase不允许键包含“ /”

这样效果更好

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
}