简体   繁体   中英

Cloud-Firestore function to stop changes to a collection/document after it has reached a limited number?

Is there a way to stop writes to a document if the amount of documents in another collection has reached a certain number? Keep in mind concurrency- multiple users writing at the same time!

Sure:

  1. Have the write to Firestore happen within a Cloud Function (callable or https)

  2. In the function, have an if clause that checks the number of documents prior to writing

  3. You'd have to also do the validation logic of whether the user has permission to write within that function, rather than through a Firestore rule.

Regarding actually counting the number of documents, the best method would depend on how many there are, and how quickly they're being written to. This SO thread addresses those issues: Cloud Firestore collection count

You can prevent writes to that document using Firebase's server-side security rules , which are automatically enforced for writes from any client SDK.

If for example you have a document with a number that must be say greater than 0 to be allowed to write a new document, you can enforce that with:

service cloud.firestore {
  match /databases/{database}/documents {
    match /orders/{order} {
      // Only allow an order for a product of there's any stock left
      allow create: 
        if get(/databases/$(database)/documents/products/$(request.resource.data.productid)).data.stock > 0
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM