【问题标题】:Firebase rule to check if newData value is over a certain amountFirebase 规则检查 newData 值是否超过一定数量
【发布时间】:2019-05-25 22:21:42
【问题描述】:

所以我在我的 firebase 实时数据库中添加规则,我需要它来检查添加的 newData 值是否超过一定数量,在这种情况下是用户在他们的 uid 下的余额。因此,如果用户的“余额”超过了正在添加的“价格”数据,则写入数据。

这是我的数据库的样子:

{
  "orders" : {
   "-Lfi6kSDLOmcvGgfiWjX" : {
        "amount" : "100",
        "price" : "0.01",
      },
  },
  "users" : {
    "GNzSciHRZAgZgIrhqIvR2vzVugj2" : {
      "balance" : "100",
    }
  }
}

这是我用来添加到数据库的代码:

firebase.database().ref('orders').push().set ({
price: '10',
amount: '1'
});

这就是规则:

   "users": {
    ".read": true,
    ".write": true
   },

 "orders": {
    ".read": true,
    ".write": "root.child('users').child(auth.uid).child('balance').val() > '0' && root.child('users').child(auth.uid).child('balance').val() > newData.child('price').val()" 
   }

在我添加 newData.child('price').val() 规则之前一切正常,这是如何使用规则的吗?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-security


    【解决方案1】:

    由于您将值存储为字符串,Firebase 将对其使用字典顺序和字符串比较运算符。我强烈建议将数值存储为实际数字,这使得规则更易于推理:

    JSON:

    {
      "orders" : {
       "-Lfi6kSDLOmcvGgfiWjX" : {
            "amount" : 100,
            "price" : 0.01,
          },
      },
      "users" : {
        "GNzSciHRZAgZgIrhqIvR2vzVugj2" : {
          "balance" : 100,
        }
      }
    }
    

    JavaScript 代码:

    firebase.database().ref('orders').push().set ({
      price: 10,
      amount: 1
    });
    

    规则:

    "orders": {
      ".read": true,
      ".write": "
        root.child('users').child(auth.uid).child('balance').val() > 0 && 
        root.child('users').child(auth.uid).child('balance').val() >= newData.child('price').val()" 
    }
    

    请注意最后一个表达式中从 >>= 的变化,因为您可能还希望在用户有足够的钱时允许写入。


    更新

    除此之外,您的规则是在 orders 本身上声明的,它们应该在特定顺序上声明低一级。

    所以:

    "orders": {
      "$orderId": {
        ".read": true,
        ".write": "
          root.child('users').child(auth.uid).child('balance').val() > 0 && 
          root.child('users').child(auth.uid).child('balance').val() >= newData.child('price').val()" 
      }
    }
    

    【讨论】:

    • 感谢您的回复,我得到了您关于使用数值的建议,并添加了 >= 但一个问题。我从 html 数字输入中获取数据(我一开始应该说)所以当使用 jquery 获取数据时,我使用 price: $("#price").val() 将数据作为字符串保存在我的数据库中。我怎样才能让它像你所说的那样将它存储为一个数值。
    • 我对数字问题进行了排序,但实际上我遇到了另一个问题,root.child('users').child(auth.uid).child('balance').val() >= newData.child('price').val() 在使用 .push().set 时似乎不起作用,它似乎只在我使用 .update 时起作用。将它与 push.set 一起使用时我收到权限警告,但它没有添加到数据库中,因为它在数据前面添加了一个新子项,我是否必须添加另一个 .child() 查询?例如,当使用 push.set 时,它会添加子 -Lfi6kSDLOmcvGgfiWjX,然后是其中的数据
    猜你喜欢
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多