I have a Firebase record "searches: 0" for each user. On some event, I'd like to add 1 to what the current count is. I've gotten this far, but for some reason, it's not working:
du.fbAddSearchCount = function() {
var usr = new Firebase(firebase_url + "/users/" + user_uid);
usr.on("value", function(snapshot) {
user = snapshot.val();
var usersRef = ref.child("users");
var fbUser = usersRef.child(user_uid);
fbUser.update( {
searches: user.searches + 1
});
}
}
Any help to get this working?
Thank you.
Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.
Lastly, it'll scale massively and automatically. Firebase Functions will just do it automatically for you based on the traffic you receive and at an incredibly low cost.
You can use transaction
var databaseRef = firebase.database().ref('users').child(user_uid).child('searches');
databaseRef.transaction(function(searches) {
if (searches) {
searches = searches + 1;
}
return searches;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With