0

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
MacD
  • 566
  • 3
  • 9
  • 27

1 Answers1

1

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);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Ok I see where you are going. I'm getting the error "ReferenceError: Can't find variable: db" however.. Any thoughts? – MacD Sep 03 '18 at 23:56
  • That's just a reference to Firebase, typically initialized with something like `var db = firebase.firestore();`. This is covered in [Get started](https://firebase.google.com/docs/firestore/quickstart) in the Firebase docs. – Frank van Puffelen Sep 04 '18 at 01:16