Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore update document without skipping values in Flutter

Currently I have a collection with a list of Users in it

In my admin app I have a button that lets me update users documents based on the current value I set which is done via this function:

onPressed: () async {
  var querySnapshots = await collection
      .where('current_pick', isEqualTo: _currentValue)
      .get();
  for (var doc in querySnapshots.docs) {
    await doc.reference.update({
      'current_streak': FieldValue.increment(1),
      'current_score': FieldValue.increment(1),
      'rank_up': true,
    });
  }
},

The function works but it updates all the values one by one, which is fine at the moment but not so sure as the user count rises

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I have noticed that very rarely it skips updating one out of three values on some users and was wondering if there is a different approach on updating values without failure ?

>Solution :

It sounds like you’ll want to use a batched write, which allows you to write to multiple document atomically.

For your code that’d look something like this:

// Get a new write batch
final batch = db.batch();

// Put the updates into the batch
for (var doc in querySnapshots.docs) {
  batch.update(doc.reference, {
    'current_streak': FieldValue.increment(1),
    'current_score': FieldValue.increment(1),
    'rank_up': true,
  });
}

// Commit the batch
batch.commit().then((_) {

Note that a batched write can contain up to 500 operations, so if you may have more than 500 documents to update, you’ll have to split it out over multiple batched writes.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading