Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a record in Firebase?

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.

like image 671
user1661677 Avatar asked Jul 15 '15 06:07

user1661677


People also ask

How do I increment a number in firestore?

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.

Does firebase automatically scale?

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.


1 Answers

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;
});
like image 81
Sunday G Akinsete Avatar answered Sep 22 '22 11:09

Sunday G Akinsete