【问题标题】:How to restrict read and write in one collection and restrict write in another collection both of which are related to same user in cloud firestore?如何限制一个集合中的读写并限制另一个集合中的写入,这两个集合都与云 Firestore 中的同一用户相关?
【发布时间】:2020-07-24 21:27:33
【问题描述】:

我在 Cloud Firestore 中有用户和配置文件集合,如下图所示。我将用户详细信息存储在用户集合中,文档 ID 作为用户的 firebase UID,以便只有特定用户可以更新和读取自己的数据,而不能更新和读取其他用户。我有用户收集的安全规则,类似于这个答案Disable querying collection in Firebase Cloud Firestore with rules 现在我的个人资料集合应该是文档的公共集合,以便可以引用这些 ID 来阅读个人资料的详细信息,但是每当用户更新其用户集合中的数据时,如果公共字段被更新,它也应该反映在个人资料文档中。我怎样才能做到这一点?

P.S:在用户文档中的字段如姓名、年龄、付款详情,而在个人资料中则如姓名和年龄。

【问题讨论】:

    标签: firebase google-cloud-firestore firebase-security


    【解决方案1】:

    您的功能要求:

    每当用户更新他们在用户集合中的数据时,它也应该是 如果公共字段被更新,则反映在配置文件中。

    您可以使用batched write,如下:

    // Get a new write batch
    var batch = db.batch();
    
    var userId = '......';
    
    var commonData = {
        name: '...',
        age: ...
    }
    
    var userRef = db.collection('users').doc(userId);
    batch.update(userRef, {paymentDetails : "...", ...commonData});  
    // We use the spread syntax, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals
    
    var profileRef = db.collection('profiles').doc(userId);
    batch.update(profileRef, commonData);
    
    // Commit the batch
    batch.commit().then(function () {
        // ...
    });
    

    write 安全规则而言,您可以将它们定义如下:

    service cloud.firestore {
      match /databases/{database}/documents {
    
        match /users/{userId} {
          allow write: if request.auth.uid == userId;
          allow ....
        }
    
        match /profiles/{userId} {
          allow write: if request.auth.uid == userId;
          allow ....
        }
    
      }
    }
    

    【讨论】:

    • 所以,我看了一些帖子,想到每当有用户文档更新时就使用云功能,你认为考虑成本和可扩展性是个好主意吗?
    • 云函数也是一个有效的替代方案。这实际上取决于您的一般应用程序架构。很难,用你分享的信息告诉你什么会更好。如果在您的前端,您拥有所有必要的数据(nameagepaymentDetails、...),那么批量写入是一个非常好的选择。
    • 是的,我在前端有这些细节。我想公开文档 ID,假设这些用户对某个帖子发表了一些评论,那么他们的参考 ID 应该在那里可以从那里访问他们的公开个人资料。
    • 这是另一个问题。您只需将用户 ID 保存在帖子的评论中即可。您将通过firebase.auth().currentUser.uid 获取用户ID,请参阅firebase.google.com/docs/auth/web/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2018-07-11
    • 2020-05-25
    相关资源
    最近更新 更多