Smooth
Smooth

Reputation: 956

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.

Upvotes: 0

Views: 584

Answers (2)

Smooth
Smooth

Reputation: 956

Was able to get it working with the following (thanks @SiddAjmera for helping me get on the right track):

  incrementChoice(choiceKey) {
    const choiceDoc:any = this.db.collection('choices').doc(choiceKey);
    choiceDoc.ref.get().then(choice => {
      let votes = choice.data().votes
      choiceDoc.update({
        votes: ++votes
      });
    });

Upvotes: 0

SiddAjmera
SiddAjmera

Reputation: 39462

Give this a try:

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

Here's a Working Sample StackBlitz for your ref.

Upvotes: 1

Related Questions