Search code examples
angularfirebaseangularfire2

Increment a value inside Firebase document using AngularFire2 @angular/fire V5


I have a document in Firebase with a value that I want to increment but I don't see anything in the documentation for Angularfire2 on how to do this.

I tried using this answer Create or increment a value with Angular2/AngularFire2 but fail because my this.db instance does not recognize the object method.

** UPDATE **

I was able to somewhat get my code to do what I want by doing the following:

incrementChoice(choiceKey) {
    this.db.doc(choiceKey).valueChanges().subscribe((choice:any) => {
      this.db.doc(`choices/${choiceKey}`)
        .update({
          votes: ++choice.votes
        });
    })
  }

The problem, however, is that I am now stuck in an infinite loop of incrementing because each time the value is incrementing the subscription kicks in and increments again. I don't know how else to get the choice vote value? Can someone help me refactor this so that I can obtain just one choice object using its key and not be bounded to the subscription when I update the value of the votes?

I understand that it's possible to get the object by fetching the entire collection but for my use case, I do not want to have to depend on the whole collection to get the object and votes value from that object. I already have the object Key.


Solution

  • Give this a try:

    this.afs.doc(`choices/${choice.key}`)
      .update({
        votes: ++choice.votes
      });
    

    Here's a Working Sample StackBlitz for your ref.