在 Firestore 规则中限制子集合中的文档数量 [英] Limit a number of documents in a subcollection in firestore rules

查看:21
本文介绍了在 Firestore 规则中限制子集合中的文档数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的请求看起来很简单:使用 Firestore 规则限制子集合中的文档数量.

My request is pretty simple in appearence : limiting the number of documents in a subcollection using Firestore Rules.

我已经知道使用 .size() 可以知道数组的大小.所以,你可能会问为什么我不使用数组来存储我的项目?好吧,我希望普通"用户无法更新我的父文档字段,但能够将文档添加到我的子集合中.

I already know that it is possible to know the size of an array using .size(). So, you may ask why I am not using an array to store my items ? Well, I want a "normal" user to not be able to update my parent document field but to be able to add a document to my subcollection.

我已经尝试这样做了:

match /slots/{slot} {
      allow read: if true;
      allow write: if getRole() == 'ADMIN';

      match /participants/{participant} {
        allow read: if true;
        allow create: if get(/databases/$(database)/documents/slots/$(slot)/participants).size() < 2;
        allow delete: if participant.data.id == request.auth.uid || getRole() == 'ADMIN';
      }
    }

但是 get(/databases/$(database)/documents/slots/$(slot)/participants) 不起作用,因为 get() 应该只使用用于获取单个文档.

But get(/databases/$(database)/documents/slots/$(slot)/participants) does not work as get() should only be used for fetching a single document.

也许我可以尝试使用云功能...

Maybe I can try something with cloud functions...

我的问题有什么解决方案吗?感谢您的帮助!

I there any solution to my problem ? Thank you for your help !

推荐答案

在一般意义上(在数据库规则和客户端 SDK 中),没有办法知道集合的大小.您可以选择将其记录在另一个由 Cloud Functions 管理的文档中.但请记住,一个文档每秒只能写入 10 次,因此繁忙的集合可能无法与用于记录大小的文档保持同步.

In a general sense (both in database rules and client SDKs) there is no way to know the size of a collection. You have the option of recording that yourself in another document that's managed by Cloud Functions. But bear in mind also that a document is limited to 10 writes per second, so busy collections might not be able to keep in sync with the document used to record size.

您还可以使用 Cloud Functions 从集合中删除文档以响应添加的新文档,但现在知道集合大小的限制将是有问题的.最好找到一种查询方式来查找要删除的文档(例如,通过时间戳)而不是依赖于集合的大小.

You could also use Cloud Functions to remove documents from a collection in response to new documents being added, but the limitation of now knowing the size of the collection will be problematic. It might be better to find a way to query to find documents to delete (for example, by timestamp) rather than depending on the size of the collection.

这篇关于在 Firestore 规则中限制子集合中的文档数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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