在Firestore规则中限制子集合中的文档数量

在Firestore规则中限制子集合中的文档数量

本文介绍了在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规则中限制子集合中的文档数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:35