Firestore update all documents in collections

后端 未结 4 763
执笔经年
执笔经年 2020-11-29 11:04

I have a firestore collections named users, each users have a generated id with a field score :

users 
    0e8X3VFL56rHBxxgkYOW
        score : 4
    3SeDjr         


        
4条回答
  •  难免孤独
    2020-11-29 11:46

    For some strange reason the accepted answer ( thehamzarocks ) wasn't working for me, none of the documents were updated. Maybe there's a bug in AngularFire2. Anyway, I decided to loop over the docs array of the QuerySnapshot instead of using its forEach method, and add each update to a batch queue. Batching bulk operations is also more efficient than sending a new update request for each update operation.

    resetScore(): Promise {
      return this.usersCollectionRef.ref.get().then(resp => {
        console.log(resp.docs)
        let batch = this.afs.firestore.batch();
    
        resp.docs.forEach(userDocRef => {
          batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
        })
        batch.commit().catch(err => console.error(err));
      }).catch(error => console.error(error))
    }
    

提交回复
热议问题