代码之家  ›  专栏  ›  技术社区  ›  ton1

如何在Firebase查询中使用startAt()?

  •  12
  • ton1  · 技术社区  · 9 年前

    enter image description here

    我想要的是检索在“15039996197”时间戳之后的消息。每个消息对象都有一个 createdAt 所有物

    我试过了 firebaseb.database().ref(`/rooms/$roomKey/messages`).startAt('15039996197') 但失败了。它返回0。我该怎么做?

    4 回复  |  直到 9 年前
        1
  •  12
  •   Gabriel Barreto    9 年前

    message createdAt . 因此,在这种情况下,您必须指定要按 创建日期 ,因此您需要这样做

    firebase.database().ref(`/rooms/$roomKey/messages`).orderByChild('createdAt').startAt('15039996197').on(//code);
    

    消息 有一个孩子叫 创建日期 15039996197 . 对查询进行排序可能会对性能有点不利,我建议大家看看。indexOn规则。

    有关更多信息,请查看 here

    希望这有帮助。

        2
  •  1
  •   Rishabh Dugar    9 年前

    因此,无论您想要获得什么数据,都会遍历整个节点。 因此,在您的情况下,要获取任何消息,您的复杂性将是O(消息数)。

    您可能希望重新构造存储数据的方式,并将createdAt放在Node而不是Child中。

        3
  •  0
  •   Jascha Huisman    6 年前

    如果您的数据库结构是这样的,您可以使用:

    firebase.database()
         .ref(`/rooms/$roomKey/messages`)
         .orderByChild('createdAt')
         .startAt('15039996197').on('value', snapshot => { /* your code here */ });
    

    firebase.database().ref(`${rooms}/${roomKey}/${timestamp}`).set("value");
    

    在这种情况下检索数据,而不是 orderByChild('createdAt') ,您将使用 orderByKey() . 由于firebase键是字符串类型,因此需要让舒尔在 .startAt()

    然后它将看起来像这样:

    firebase.database()
         .ref(`/rooms/$roomKey/messages`)
         .orderByKey()
         .startAt(`${15039996197}`).on('value', snapshot => { /* your code here */ });
    
        4
  •  -1
  •   local_klaus    8 年前

    firebase.database().ref('/rooms/$roomKey/messages')
                    .orderByChild('createdAt')
                    .startAt('150399')
                    .endAt('1503999\uf8ff')
                    .on('value', function (snapshot) {
                        var key = snapshot.key,
                        data = snapshot.val();
                        console.log(key + ': ' + JSON.stringify(data))
                    });
    

    确保设置endAt()。

    推荐文章