How to increment a record in Firebase?

17,289

Solution 1

There's a new method ServerValue.increment()in firebase JavaScript SDK v7.14.0

It's better for performance and cheaper since no round trip is required.

See here

Added ServerValue.increment() to support atomic field value increments without transactions.

API Docs here

Usage example:

firebase.database()
    .ref('users')
    .child(user_uid)
    .child('searches')
    .set(firebase.database.ServerValue.increment(1))

Or you can decrement, just put -1 as function arg like so:

firebase.database()
    .ref('users')
    .child(user_uid)
    .child('searches')
    .set(firebase.database.ServerValue.increment(-1))

Solution 2

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;
});

Solution 3

For the Realtime Database the use of transaction seems to be the best way to do it. See the answer from Sunday G Akinsete

From his answer and the related comments:

firebase
    .database()
    .ref('users')
    .child(user_uid)
    .child('searches')
    .transaction(function(searches) {
        return (searches || 0) + 1
    })

For the Firestore Database you can use the Firebase Sentinel values to increment/decrement a value that without having to fetch it first

Increment

firebase
    .firestore()
    .collection('users')
    .doc('some-user')
    .update({ 
         valueToIncrement: firebase.firestore.FieldValue.increment(1) 
    })

Decrement

firebase
    .firestore()
    .collection('users')
    .doc('some-user')
    .update({ 
        valueToDecrement: firebase.firestore.FieldValue.increment(-1) 
    })

Documentation Reference

Solution 4

For the Realtime Database, using increment() works well for this - here's a client-side JS example that uses the newer ESM syntax

import { getDatabase, ref, set, increment } from  "https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js";


// Initialize Firebase
const firebaseConfig = { ...};
const app = initializeApp(firebaseConfig);


const writeFavNameData = name => {
    const db = getDatabase();
    const favRef = ref(db, 'favorites/' + name);
    set(favRef, {
            name,
            likes: increment(1)
    });
};

writeFavNameData("Petunia"); // `likes` is initialized at 1
writeFavNameData("Petunia"); // `likes` is now 2
Share:
17,289
user1661677
Author by

user1661677

Updated on June 19, 2022

Comments

  • user1661677
    user1661677 about 2 years

    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.

  • david-ojeda
    david-ojeda over 7 years
    Your code will not work when searches = 0. You can instead do this: return (searches || 0) + 1;
  • Anantha Raju C
    Anantha Raju C almost 7 years
    provide an explanation to your answer
  • Ivan Rubinson
    Ivan Rubinson over 5 years
    What environment COMPILES javascript?
  • ntcho
    ntcho over 4 years
    Nice, but the original question seems to be using Realtime Database instead of Firestore.
  • Mathias Gilson
    Mathias Gilson over 4 years
    Ah yes I didn't notice, I updated the answer to specify that's for Firestore only. Thank you !
  • Frank van Puffelen
    Frank van Puffelen about 4 years
    Great update Oleg. There is now indeed also an increment operation for the Realtime Database, which performs significantly better than using a transaction (see my test here).
  • Partik
    Partik over 2 years
    Thanks for showing the Firebase 9 syntax. I couldn't find any examples in the docs for how to use increment like this.