【问题标题】:firebase use orderByChild on child's child's valuefirebase 对孩子的孩子的价值使用 orderByChild
【发布时间】:2018-01-22 17:01:31
【问题描述】:

我正在使用 react-native 构建应用程序。我想按createdAt 值降序对chatList 进行排序。

这是我的结构:

{
   "chatList": {
       "L3RDhCUvTVBk--KKgCl" : {
           "lastMessage": {
               "createdAt": 1516638900725
           }
       },
       "L3RDhCUvTVBk--KKgC1" : {
           "lastMessage": {
               "createdAt": 1516638920725
           }
       }
   }
}

另外,我需要索引这个结构吗?

【问题讨论】:

    标签: javascript firebase react-native firebase-realtime-database


    【解决方案1】:

    如果您的最后一条消息总是在聊天下方的lastMessage/createdAt(例如/chatList/*/lastMessage/createdAt),那么您可以使用以下方式查询聊天列表:

    firebase.database.reference("chatList").orderByChild("lastMessage/createdAt")
    

    但是,您不能按降序排列。因此,您要么必须在客户端反转结果,要么存储倒置的时间戳。有关更多信息,请参阅我的答案:firebase -> date order reverse

    如果 lastMessage 实际上是动态的(chatList 下的每个子代都不同),那么很遗憾,您无法从当前结构中获得结果,您需要扩充数据以允许查询。

    如果您想获取按最后更新日期排序的聊天列表,则需要在数据库中准确存储:聊天列表及其最后更新日期。

    {
      "chatUpdates": {
        "L3RDhCUvTVBk--KKgCl": 1516638900725
        "L3RDhCUvTVBk--KKgC1": 1516638920725
      }
    }
    

    这是一个附加数据结构,纯粹是为了让您的用例。因此,现在您需要在添加消息时同时更新chatListchatUpdates。要了解有关有效方法的更多信息,请参阅How to write denormalized data in Firebase

    一些相关问题:

    【讨论】:

    • 这种嵌套属性的语法是否正式记录在任何地方?如果没有,那就是一个文档错误。
    • 它与多位置更新同时引入:firebase.googleblog.com/2015/09/… 并出现在旧文档中:firebase.com/docs/web/guide/…。但今天的文档中确实完全缺少它,所以......是的......时间到file a bug report
    • 我尝试使用firebase.database.reference("chatList").orderByChild("lastMessage/createdAt")。但是,响应没有排序
    • 我还需要做些什么来真正对chatList 进行排序吗?比如.indexOn
    • 请更新您的问题以显示您尝试过的代码,包括您如何处理快照。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2018-03-19
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多