How to increment a record in Firebase?

后端 未结 5 750
余生分开走
余生分开走 2020-12-05 19:42

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

5条回答
  •  感动是毒
    2020-12-05 20:21

    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

提交回复
热议问题