简体   繁体   English

在 Firebase 中设置子项的最大数量

[英]Set a maximum number of children in Firebase

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.我不知道在 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.我的目标是将用户的 UID 写入服务器,如果值(我可以在客户端搜索可用点,该值可以是 0 到 1000 之间的 Int)是免费的,则被接受。 It should be rejected when all spots are taken (1000 children in a node).当所有的点都被取走(一个节点中有 1000 个孩子)时,它应该被拒绝。 I hope someone can help me out figuring out the needed validation rules.我希望有人可以帮助我找出所需的验证规则。 Thank you.谢谢你。

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)这里已经有关于 SO 的指南: 限制可以写入路径的记录数(参考安全规则中的其他路径)

Or you could use Cloud Functions for Firebase to implement a database trigger that both:或者您可以使用Cloud Functions for Firebase来实现一个数据库触发器

  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.检查子项计数以确保新子项可用于添加,如果无效则删除它(或其他子项)。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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