Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore update all documents in collections

Tags:

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

users      0e8X3VFL56rHBxxgkYOW         score : 4     3SeDjrgAWMmh3ranh2u         score : 5 

I use redux-firestore and i want to reset all my users score at 0, something like

firestore.update({ collection: 'users' }, { score : 0 } 

I can't achieve this because update method need a document id

Do you know how to do this ?

like image 225
Lionel B Avatar asked Jul 23 '18 14:07

Lionel B


People also ask

How do I update firestore files?

Firestore Update Entire Document getDatabase() → where we want to update a document. doc() → where we'll be passing references of database, collection and ID of a document that we want to update. setDoc() → where we actually pass new data that we want to replace along with the doc() method.

Can firestore update multiple documents matching a condition using one query?

Cloud Firestore does not support the equivalent of SQL's update queries.


2 Answers

You can get all the documents in the collection, get their id's and perform updates using those id's:

db.collection("cities").get().then(function(querySnapshot) {     querySnapshot.forEach(function(doc) {         doc.ref.update({             capital: true         });     }); }); 
like image 93
thehamzarocks Avatar answered Sep 29 '22 10:09

thehamzarocks


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<void> {   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)) } 
like image 25
jsaddwater Avatar answered Sep 29 '22 10:09

jsaddwater