faccio
faccio

Reputation: 1014

How to delete a field in Firestore document checking condition with Flutter?

I'm working with Flutter and Firebase. I have the following document: enter image description here

I'd like to build a function that checks this specific document and delete all the Map (e.g. test1) where the field shouldDelete contains the number 1. How could I implement this function?

void check(
  String documentId,
) {
 final DocumentReference<Map<String, dynamic>> mydoc = 
  FirebaseFirestore.instance.collection('collection').doc(documentId);
}

Upvotes: 0

Views: 253

Answers (1)

faccio
faccio

Reputation: 1014

I managed to find the solution:

void convalida(
    String documentId,
    ) {
  final DocumentReference<Map<String, dynamic>> mydoc= 
   FirebaseFirestore.instance.collection('collection').doc(documentId);
  mydoc.get().then((value) =>
      value.data()!.forEach((key, value) {
        if(value["shouldDelete"]==1 ) {mydoc.update({key:FieldValue.delete()});}
      }
      )
  );

}

In this way we are not deleting only shouldDelete field but al the test1 Map. Hope this could help someone in the future.

Upvotes: 1

Related Questions