Home > OS >  How to delete/update specified index in an array object from firestore with flutter
How to delete/update specified index in an array object from firestore with flutter

Time:12-03

I am facing a delete/update issue with firestore array object.This is my subcollection looks like questionnaire subcollection

I have an option in my flutter web app to delete or update the questions. questionnaire is an array and all the indexes are map. Is there any possible way to delete or update the indexes directly? I have seen a couple of solutions where all the array elements are read back to the application and remove the item we need to delete and add the items that need to be updated. I will be having around 150 questions in an array, so I think it is not an efficient way from a performance point of view. So I have tried couple of methods to delete the data

FirebaseFirestore.instance
          .collection('exam')
          .doc(examDocID)
          .collection('questionnaire')
          .doc(_questionnaireDocID)
          .update({
        'questionnaire': {'$index': FieldValue.delete()}
      }).then((_) {
        print('question deleted');
      }).catchError((onError) {
        print(onError);
      });

and

'questionnaire.$index':  FieldValue.delete()
'questionnaire': FieldValue.arrayRemove([index])

It used to delete all elements in the array from most of my tries. Could someone please let me know is there any workaround to fix this issue

CodePudding user response:

Is there any possible way to delete or update the indexes directly?

No, there is not.

I have seen a couple of solutions where all the array elements are read back to the application and remove the item we need to delete and add the items that need to be updated.

Yes, that way to handle such a situation.

I will be having around 150 questions in an array, so I think it is not an efficient way from a performance point of view.

It's not inefficient but the opposite. Besides that, when it comes to billing it implies only a document read, and a document write, no matter how many items are you adding or deleting from the array in a single go.

If you want to delete a specific object from the array using FieldValue.delete(), you should use all the data in the object and not partial data. I have even written an article regarding updating an array of objects in Cloud Firestore:

  • Related