Home > Blockchain >  Would like to update the firestore database of certain document based on an if statement
Would like to update the firestore database of certain document based on an if statement

Time:04-06

I'm trying to update certain documents 'avail' field to true only if the toolCount method I applied is more than 1. Each document is a different tool I am counting their quantity based on their toolName meaning if I have 2 Screens in toolName field then

Img of firebase:

Code:

  @override
  Future countTools() async {
    try {
      FirebaseFirestore.instance.collection('Tools').get().then((value) {
        var toolNamesCounted = Map();
        List toolNames = [];

        value.docs.forEach((data) {
          var doc = data.data();

          toolNames.add(doc['toolName']);
        });

        toolNames.forEach((e) {
          if (!toolNamesCounted.containsKey(e)) {
            toolNamesCounted[e] = 1;
          } else {
            toolNamesCounted[e]  = 1;
          }
        });
      });
    } catch (e) {
      print(e);
    }
  }

CodePudding user response:

You need to collect doc ids with the same field name and best way to update multiple docs is using batched writes

FirebaseFirestore.instance.collection('Tools').get().then((value) {
  WriteBatch batch = FirebaseFirestore.instance.batch();

  List<dynamic> toolNamesCounted = [];
  List<dynamic> toolNames = [];

  value.docs.asMap().forEach((i, data) {
    var doc = data.data();

    toolNames.add({
      'name': doc['toolName'],
      'id': value.docs[i].reference.id,
    });
  });

  // collect ids if same toolName
  toolNames.forEach((e) {
    final match = toolNamesCounted.indexWhere((element) => element['name'] == e['name']);

    // if found collect ids
    if (match >= 0) {
      toolNamesCounted[match]['ids'].add(e['id']);
    } else {
      // if not found add first record
      toolNamesCounted.add({
        'name': e['name'],
        'ids': ['${e['id']}'],
      });
    }
  });

  toolNamesCounted.forEach((e) {
    // if collected ids array more than 2 add batches
    if (e['ids'].length >= 2) {
      e['ids'].forEach((e) {
        batch.update(FirebaseFirestore.instance.collection('Tools').doc(e), {'avail': true});
      });
    }
  });

  // update all the docs
  batch.commit();
});
  • Related