Cloud Functions for Firebase: Increment Counter

10,814

Definitely! In fact, that's exactly how it's done in this code sample, although with a few small differences:

exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => {
  var collectionRef = event.data.ref.parent;
  var countRef = collectionRef.parent.child('likes_count');

  return countRef.transaction(function(current) {
    if (event.data.exists() && !event.data.previous.exists()) {
      return (current || 0) + 1;
    }
    else if (!event.data.exists() && event.data.previous.exists()) {
      return (current || 0) - 1;
    }
  });
});

Notably, this sample handles both an increment and a decrement case depending on whether the child node is being created or deleted.

Share:
10,814
J. Adam Connor
Author by

J. Adam Connor

Professional web dev.

Updated on June 06, 2022

Comments

  • J. Adam Connor
    J. Adam Connor almost 2 years

    Is it acceptable to increment a counter with a realtime database trigger using transaction?

    exports.incPostCount = functions.database.ref('/threadsMeta/{threadId}/posts')
    .onWrite(event => {
        admin.database().ref('/analytics/postCount')
        .transaction(count => {
            if (count === null) {
                return count = 1
            } else {
                return count + 1
            }
        })
    });