Search code examples
javascriptfirebasegoogle-cloud-firestoreangularfire5

Angularfire Increment transaction


Im having trouble incrementing a count of post "likes". The following is what I have right now:

addLike(pid, uid) {
    const data = {
      uid: uid,
    };
    this.afs.doc('posts/' + pid + '/likes/' + uid).set(data)
 .then(() => console.log('post ', pid, ' liked by user ', uid));

  const totalLikes = {
         count : 0 
        };
        const likeRef = this.afs.collection('posts').doc(pid);
         .query.ref.transaction((count => {
           if (count === null) {
               return count = 1;
            } else {
               return count + 1;
            }
        }))
        }

this obviously throws and error.

My goal is to "like" a post and increment a "counter" in another location. Possibly as a field of each Pid?

What am I missing here? I'm certain my path is correct..

Thanks in advance


Solution

  • You're to use the Firebase Realtime Database API for transactions on Cloud Firestore. While both databases are part of Firebase, they are completely different, and you cannot use the API from one on the other.

    To learn more about how to run transactions on Cloud Firestore, see updating data with transactions in the documentation.

    It'll look something like this:

    return db.runTransaction(function(transaction) {
        // This code may get re-run multiple times if there are conflicts.
        return transaction.get(likeRef).then(function(likeDoc) {
            if (!likeDoc.exists) {
                throw "Document does not exist!";
            }
    
            var newCount = (likeDoc.data().count || 0) + 1;
            transaction.update(likeDoc, { count: newCount });
        });
    }).then(function() {
        console.log("Transaction successfully committed!");
    }).catch(function(error) {
        console.log("Transaction failed: ", error);
    });