简体   繁体   中英

Flutter: How to remove a specific array data in firebase

I'm having a problem right now in firebase. Where I try to delete/remove a specific array data. What is the best way to do it? Ps. I'm just new in firebase/flutter.

My database structure:

在此处输入图像描述

Data that i'm trying to remove in my database structure(Highlighted one):

在此处输入图像描述

First create a blank list and add element in the list which you want to remove then Update using below method

Note : For this method you need the documennt id of element you want to delete

var val=[];   //blank list for add elements which you want to delete
val.add('$addDeletedElements');
 Firestore.instance.collection("INTERESTED").document('documentID').updateData({

                                        "Interested Request":FieldValue.arrayRemove(val) })

Update: Much has changed in the API, although the concept is the same.

var collection = FirebaseFirestore.instance.collection('collection');
collection 
  .doc('document_id')
  .update(
  {
    'your_field': FieldValue.arrayRemove(elementsToDelete),
  }
);

This will help you to add and remove specific array data in could_firestore.

getPickUpEquipment(EquipmentEntity equipment) async{


final equipmentCollection = fireStore.collection("equipments").doc(equipment.equipmentId);

final docSnap=await equipmentCollection.get();

List queue=docSnap.get('queue');

if (queue.contains(equipment.uid)==true){

  equipmentCollection.update({

    "queue":FieldValue.arrayRemove([equipment.uid])

  });

}else{


  equipmentCollection.update({

    "queue":FieldValue.arrayUnion([equipment.uid])

  });

}

}

Example

ezgif com-crop(1)

Firestore does not provide a direct way to delete an array item by index. What you will have to do in this case is read the document, modify the array in memory in the client, then update the new contents of the field back to the document. You can do this in a transaction if you want to make the update atomic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM