Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire2

AngularFire UPDATE -> WHERE


I not find something here. My question is how UPDATE a document returned in WHERE clausule in AngularFire:

constructor(private db: AngularFirestore) { }

var path = this.db.collection('users').doc('type').collection('customer')
.ref.where('name', '==', 'roger');

how UPDATE this user ?

var query = path.set/update..? 

not working.


Solution

  • I do not understand how the previous answer got accepted because the behaviour is wrong and ends in an infinite loop (snapshotChanges() triggers update(), which again, triggers snapshotChanges() as it has subscribed to it.) Also, this angularfire synatx is outdated so I will point out a different approach.

    To achieve the behaviour OP is looking for, the best practice is to store the document ID in the document itself. When creating an item, add() returns a DocumentReference, which includes the ID of the just inserted item.

    An example implementation would be:

     create(user) {
        return new Promise<any>((resolve, reject) => {
          this.db
            .collection('users')
            .doc('type')
            .collection('customer')
            .add(user)
            .then(res => {
              this.updateUserId(res.id);  
            }, err => reject(err));
        });
      }
    
      updateUserId(id: string) {
        return this.db
          .collection('users')
          .doc('type')
          .collection('customer')
          .doc(id)
          .set({ id: id }, { merge: true });
      }
    

    In this case, the user would be created and immediately afterwards, the id field of the user object would be updated (as the Firestore document ID is only available after insertion). Now the user can easily be updated via the user's document ID.