How to increment a record in Firebase?
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;
});
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
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))