user12075070
user12075070

Reputation:

How to update document field based on different field value in that document

I have a collection of Users and in there there are 4 fields:

enter image description here

Currently I have a button that increments currentScore of every user by 1 when clicked

Future _getUsersAndUpdate() async {
var querySnapshots = await collection.get();
for (var doc in querySnapshots.docs) {
  await doc.reference.update({
    'currentScore': FieldValue.increment(1),
  });
}

I was wondering how can I increment currentScore by 1 only if currentPick field is set to 1 as well, so every document with a currentPick == 1 should get their currentScore incremented by 1 ?

Upvotes: 0

Views: 357

Answers (1)

Salih Can
Salih Can

Reputation: 1783

if I right understand your problem, below lines might be solution your problem.

Future<void> _getUsersAndUpdate() async {
    final collectionRef = FirebaseFirestore.instance.collection('users').where('currentPick', isEqualTo: 1);
    final users = await collectionRef.get();
    if(users.docs.isEmpty) return;
    users.docs.forEach(
      (doc) async {
        await doc.reference.update(
          {
            'currentScore': FieldValue.increment(1),
          },
        );
      },
    );
  }

Upvotes: 1

Related Questions