1

I need to limit the number of documents a user can have in a collection.

I expect that having a limit of let's say 100 documents when a user tries to create the document 101 gets an error.

Is there a way of doing this using firestore security rules ?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Razvan
  • 21
  • 1
  • 3

1 Answers1

1

Security rules don't have the capability to count the number of documents in a collection. In fact, counting documents in Firestore is, in general, is kind of a difficult problem that typically requires some support from a product like Cloud Functions.

If you want to get something like this to work, you will have to write some Firestore triggers in Cloud Functions that manages the count of documents by triggering some code when a document is created or deleted. This count would have to be stored in another document in another collection. Then, the contents of that document could be used in security rules to limit client access.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Keep in mind that there's a latency in a Cloud Function trigger, so, the count field on a document is most probably not yet updated when the security rules evaluate it. You can, however, offset it so that the Security Rules evaluate it correctly. – Jeboy Feb 16 '20 at 08:28
  • 1
    @Jeboy Actually, for low volume writes, it's perfectly doable to keep a transactionally accurate count, enforced by security rules, using the solution in this answer: https://stackoverflow.com/questions/59924062/how-do-you-force-a-firestore-client-app-to-maintain-a-correct-document-count-for – Doug Stevenson Feb 16 '20 at 08:31
  • Whatever the size of the write transaction, it has 3 to 4-second latency (for just 1 update operation) before the trigger kicks-in, it is documented here: https://firebase.google.com/docs/functions/firestore-events "It can take up to 10 seconds for a function to respond to changes in Cloud Firestore.". So, Security Rules will always run first. – Jeboy Feb 19 '20 at 02:15
  • @Jeboy https://stackoverflow.com/questions/59924062/how-do-you-force-a-firestore-client-app-to-maintain-a-correct-document-count-for – Doug Stevenson Feb 19 '20 at 02:31
  • `get(/databases/$(database)/documents/messages-stats/data).data.count + 1` That's what I'm saying to offset, in my first comment – Jeboy Feb 20 '20 at 03:20