firebase.database().ref("/user/" user.uid).set({
email:user.email,
points:"500",
uid: user.uid
})
can i compare the points in my database and points needed and execute the task? Like if the user have 500 points in database but it is required 500 points to carry out an operation on web app is it possible to do so? Any suggestions would be appreciated.
CodePudding user response:
If you want to perform an operation on a path in the database based on its current value, you'll want to 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
}
})
As said in my answer your previous question, I recommend storing the value of points as a number, so that you don't have to parse it in your code and so that numeric operations become possible on it.
I recommend spending some time reading the Firebase documentation at this point. A few hours spent there now will avoid many such questions going forward.
In addition to (and possibly instead of) this client-side code, you'll also want to validate the points value in your database's security rules. For example, if points must always be a positive number:
{
"rules": {
...
"user": {
"$uid": {
"points": {
".validate": "newData.isNumber() &&
newData.val() >= 0"
}
},
}
}
}