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
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 ?
CodePudding user response:
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.