如何比较 firebase 实时数据库数据(子值)
How can I compare firebase realtime database data (child values)
firebase.database().ref("/user/" + user.uid).set({
email:user.email,
points:"500",
uid: user.uid
})
我可以比较我数据库中的点数和需要的点数并执行任务吗?就像如果用户在数据库中有 500 点,但需要 500 点才能在 Web 应用程序上执行操作,是否可以这样做?如有任何建议,我们将不胜感激。
如果要根据数据库中的当前值对路径执行操作,则需要 use a transaction:
firebase.database().ref("user").child(user.uid).child("points")
.transaction((currentValue) => {
if (parseInt(currentValue) > 500) {
... do you operation and currentValue and return the result to be written to the database
}
})
正如我在回答您之前的问题时所说,我建议将点的值存储为数字,这样您就不必在代码中解析它,并且可以对其进行数字运算。
我建议此时花一些时间阅读 Firebase 文档。现在在那里花几个小时将避免许多此类问题的发生。
除了(也可能代替)此 client-side 代码之外,您还需要 validate the points value 数据库的安全规则。例如,如果点必须始终为正数:
{
"rules": {
...
"user": {
"$uid": {
"points": {
".validate": "newData.isNumber() &&
newData.val() >= 0"
}
},
}
}
}
firebase.database().ref("/user/" + user.uid).set({
email:user.email,
points:"500",
uid: user.uid
})
我可以比较我数据库中的点数和需要的点数并执行任务吗?就像如果用户在数据库中有 500 点,但需要 500 点才能在 Web 应用程序上执行操作,是否可以这样做?如有任何建议,我们将不胜感激。
如果要根据数据库中的当前值对路径执行操作,则需要 use a transaction:
firebase.database().ref("user").child(user.uid).child("points")
.transaction((currentValue) => {
if (parseInt(currentValue) > 500) {
... do you operation and currentValue and return the result to be written to the database
}
})
正如我在回答您之前的问题时所说,我建议将点的值存储为数字,这样您就不必在代码中解析它,并且可以对其进行数字运算。
我建议此时花一些时间阅读 Firebase 文档。现在在那里花几个小时将避免许多此类问题的发生。
除了(也可能代替)此 client-side 代码之外,您还需要 validate the points value 数据库的安全规则。例如,如果点必须始终为正数:
{
"rules": {
...
"user": {
"$uid": {
"points": {
".validate": "newData.isNumber() &&
newData.val() >= 0"
}
},
}
}
}