Reputation: 471
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):
Upvotes: 8
Views: 11750
Reputation: 545
I had also experienced this issue and below is how I solved it.
My case description
I wanted to remove cart item from a user collection . Below is how User my collection looks like
Future removeItemFromCart(OrderModel order) async {
try {
var userId = _firebaseAuth.currentUser?.uid;
final collection = FirebaseFirestore.instance
.collection(FirestoreConstants.pathUserCollection)
.doc(userId);
final docSnap = await collection.get();
List cart = docSnap.get('cart');
List item = cart
.where((element) => element['orderId'].contains(order.orderId))
.toList();
collection.update({'cart': FieldValue.arrayRemove(item)});
Fimber.d("REMOVED unit ${order.unit?.unitName} $userId");
PaceUser? user = await getUserCart();
return user;
} on FirebaseAuthException {
rethrow;
}
return null;}
The above code snippet solved it for me.
Happy coding
Upvotes: 0
Reputation: 2676
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
Upvotes: 2
Reputation: 267554
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),
}
);
Upvotes: 6
Reputation: 239
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) })
Upvotes: 16
Reputation: 317467
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.
Upvotes: 4