Set a maximum number of children in Firebase

橙三吉。 提交于 2020-05-23 11:02:50

问题


There are some other (older) questions about this, but since they already are a few years old, I am curious if there have been an update about this. I want to animate a lottery, in which users can buy tickets. Everything is going well, but I want to make sure there are never more than a thousand sold tickets. It has to be server side, and these are my rules:

  "Lottery": {
    ".read": "auth != null",
    ".write": "auth != null",
      "counter": {
        ".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 1000 && ((!data.exists() && newData.val() === 1) || (newData.val() === data.val()+1))"
      },
        "tickets":{
          "root.child('Lottery/counter/').val() === someValueYouNeedItToEqual"
        }
  }

I do not know what to write at someValueYouNeedItToEqual. I am concerned about the working of this system. My goal is to write the user's UID to the server, and gets accepted if the value (I can search client side for available spots, the value can be a Int between 0 and 1000) is free. It should be rejected when all spots are taken (1000 children in a node). I hope someone can help me out figuring out the needed validation rules. Thank you.


回答1:


There is this guidance already here on SO: Limit number of records that can be written to a path (reference other paths in security rules)

Or you could use Cloud Functions for Firebase to implement a database trigger that both:

  1. Increments/decrements a child count (within in a transaction to be safe) as children come and go.
  2. Checks that child count to make sure the new child is valid for addition, and deletes it (or some other child) if not.



回答2:


You're getting the error because the

"root.child('Lottery/counter/').val()"

expression doesn't return a boolean. It returns the value of whatever is stored at that reference. You can squash the error by trying something like

"root.child('Lottery/counter/').val() === someValueYouNeedItToEqual"


来源:https://stackoverflow.com/questions/43400490/set-a-maximum-number-of-children-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!