How to increment a record in Firebase?
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)
})
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
user1661677
Updated on June 19, 2022Comments
-
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 over 7 yearsYour code will not work when
searches = 0
. You can instead do this:return (searches || 0) + 1;
-
Anantha Raju C almost 7 yearsprovide an explanation to your answer
-
Ivan Rubinson over 5 yearsWhat environment COMPILES javascript?
-
ntcho over 4 yearsNice, but the original question seems to be using Realtime Database instead of Firestore.
-
Mathias Gilson over 4 yearsAh yes I didn't notice, I updated the answer to specify that's for Firestore only. Thank you !
-
Frank van Puffelen about 4 yearsGreat 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 over 2 yearsThanks for showing the Firebase 9 syntax. I couldn't find any examples in the docs for how to use increment like this.