如何在一个节点下存储公共/私有数据,并仍然查询整个节点 [英] How to store public/private data under a node, and still query the entire node

查看:68
本文介绍了如何在一个节点下存储公共/私有数据,并仍然查询整个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据存储在$user下,其中某些数据可供公众读取,而某些数据仅可由用户读取.安全规则如下所示:

I would like to store data under a $user where some data is readable by the public, and some data is readable only by the user. The security rules would look something like this:

{
  "rules": {      
    "users": {
      "$uid": {
        "public":{
          ".read": "auth != null",
        },
        "private": {
          ".read": "$uid === auth.uid"
        }
      }
    }
  }
}

但是,由于安全规则不是过滤器,如果我是试图在users/$user读取的$user,读取将失败,对吗?有没有一种方法可以做到这一点,或者在尝试获取实际用户的所有$user信息时,我总是需要同时在users/$user/publicusers/$user/private处进行读取吗?

However, since security rules are not filters, if I were the $user trying to read at users/$user, the read would fail, correct? Is there a way to accomplish this or will I always need to perform a read at both users/$user/public and users/$user/private when trying to obtain all $user info for the actual user?

请注意,我要避免重复数据,以减少保持与源节点保持最新的重复数据的需求,并减少删除源节点时的db卫生状况.我的模式是唯一键是唯一的重复数据,它们始终指向源节点作为查询的位置.

Note that I want to avoid duplicating data in order to reduce the need to keep duplicate data current with the source node, as well as reduce db sanitation when source nodes are deleted. My schema is such that unique keys are the only duplicate data, which always point to a source node as the place to query from.

推荐答案

如果您一次只读取一个用户的信息,那么您提出的结构将可以正常工作-您可以在阅读公众信息时随时添加/public信息,或者在以用户身份访问并想同时读取公共和私有信息时直接读取$uid节点.

The structure you have proposed will work fine if you only ever read one user's information at a time -- you can simply always add /public when reading the public information, or read the $uid node directly when accessing as the user and wanting to read both public and private.

但是,如果您打算进行任何类型的查询,则此数据结构将根本无法工作,因为在读取公共数据而不读取私有数据的情况下将无法进行查询.相反,您需要将publicprivate提升到$uid级别之上:

If, however, you plan to do any kind of querying, this data structure simply won't work as there will be no way to query while reading the public data without reading the private data. Instead, you would need to hoist the public and private up above the $uid level:

users
  - public
    - $uid
  - private
    - $uid

到这一点,是的,您必须进行两次读取才能访问这两个信息位.不过请记住几件事:

Once you get to this point, yes, you'll have to do two reads to access both bits of information. Remember a few things though:

  1. 私有信息只能由根据您的规则进行创作的用户读取,因此,只要用户登录,您就可以轻松地在此单个节点上设置侦听器,然后您将始终拥有它.
  2. Firebase通过正在进行的实时连接进行连接,这意味着进行多次读取的费用可能没有您想象的那么昂贵.

关于重复数据要考虑的另一件事是 Firebase的云函数可以通过处理同步更新而无需在客户端中编写代码,从而使非规范化变得非常轻松.

Another thing to consider regarding duplicate data is that Cloud Functions for Firebase can make denormalization pretty painless by handling the sync-on-update without having to code around it in the client.

这篇关于如何在一个节点下存储公共/私有数据,并仍然查询整个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆