【问题标题】:firebase rules path containing generated id包含生成的 id 的 firebase 规则路径
【发布时间】:2019-09-11 08:49:37
【问题描述】:

我正在尝试设置我的 firebase 规则,因此我正在尝试按时间对消息进行排序,但我未能代表路径。

我的数据:

Firebase 规则:

{  
"rules": {
    ".read": true,
    ".write": true,
    "conversations": {
            "messages":{
            ".indexOn": ["time"]
          } 
    }
  }
}

component.ts (Angular 5) (Angularfire 5.0.0-rc.4)

到目前为止,我一直在客户端订购我的消息,并试图在后端找到如何做到这一点。

getMessages(id) {
      this.db.list('/conversations/' + id+ '/messages') 
      //, ref => ref.orderByChild('time')
      .valueChanges()

      .pipe(
        tap(messages => {
          messages.sort(
            (obj1: any, obj2: any) => {
              if (obj1.time > obj2.time) {
                return 1;
              }
              if (obj1.time < obj2.time) {
                return -1;
              }
              return 0;
            }
          )
        })
      )
      .subscribe(
        (messages: any) => {
        this.messages = messages;
        console.log("RECUUUUU", messages);

        this.scrollToBottom();
      },
        (error)=>{
          console.log("error getMessages");

        }
      )
  }

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-security


    【解决方案1】:

    生成的路径通常由规则中的$ 变量表示。例如。任何以$ 开头的规则都适用于该位置下所有不匹配的节点。

    因此,在您的情况下,为所有用户的 time 属性索引所有消息:

    {  
      "rules": {
        ".read": true,
        ".write": true,
        "conversations": {
          "$uid": {
            "messages":{
              "$messageid": {
                ".indexOn": ["time"]
              } 
            }
          }
        }
      }
    }
    

    确切的 $uid$messageid 是变量名,这意味着您可以在声明变量的规则中使用它们的值(以及在执行该规则时捕获的值)。

    【讨论】:

    • 我仍然得到未按时间排序的数据,它们仍然按 messageId 排序:(我发现的前面解决方案是通过在管道中排序数据(map ...),我想把它在后端级别(firebase)
    • 创建索引不会自动对项目进行排序,它只是允许 Firebase 在服务器而不是客户端对您的请求进行排序。您必须通过调用orderBy... 方法之一在查询中执行此操作。如果您在完成这项工作时遇到问题,请将最少的 代码 也添加到您的问题中。
    • 您对数据库的调用未指定任何顺序。另请注意,您的一个节点将时间戳记为字符串,而其他节点将时间戳记为数字。这也会影响排序顺序。
    猜你喜欢
    • 2017-02-05
    • 2015-08-17
    • 2017-11-12
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多