【问题标题】:Firestore: Round-robin access to document in collectionFirestore:循环访问集合中的文档
【发布时间】:2019-08-16 06:58:54
【问题描述】:

我想做一些非常简单的事情,但不确定使用 Firestore 的最佳方法。

我有一个ads 收藏。

每次访问ad 时,我都想更新accessed 属性时间戳,以便只显示最长时间未显示的广告。

我的安全规则只允许携带有效载荷为admin:true 的令牌的用户创建/修改ads

因此,在应用内,我无法在每次访问广告时更新时间戳,因为用户不是管理员。

我考虑为此创建一个函数,但意识到没有 onGet 函数可以让我这样做 (https://firebase.google.com/docs/functions/firestore-events)

无论如何,我认为不允许任何用户修改单个属性。

使用 Firestore 执行此操作的合适方法是什么?

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    您可以通过创建一个非常全面的规则验证来解决这个问题,您可以检查除accessed 之外的所有字段是否未更改。您可以使用custom claims 实现管理员角色概念,如the answer on this post 中所述。

    检查除accessed之外的所有字段是否未更改需要您一一列出并检查所有字段。

    service cloud.firestore {
      match /databases/{database}/documents {
    
        match /ads/{id} {
            allow read: if true; 
          allow write: if request.auth.token.admin == true 
                || (request.resource.data.someField == resource.data.someField
            && request.resource.data.anotherField == resource.data.anotherField);
        }
      }
    }
    

    另一种方法是创建一个与the Unix touch command 类似的callable cloud function。每次阅读广告时,您只需从客户那里调用它,您就可以在该函数内安全地更新帖子上的 accessed 字段。

    export const touchAd = functions.https.onCall((data, context) => {
        const adId = data.id;
        return admin.firestore().collection('ads').doc(adId).update({
            accessed: firebase.firestore.FieldValue.serverTimestamp(),
        }));
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      相关资源
      最近更新 更多