How can I delete an array of array of objects from Firestore? I want to delete it inside a list.generate
Here is my database structure, I want to delete [{street A, number 25}]
List.generate(
...
IconButton(
icon: const Icon(CupertinoIcons.trash),
onPressed: () async {
try {
await FirebaseFirestore.instance
.collection('users')
.doc(data['uid'])
.update(
{
'adress':
FieldValue.arrayRemove(
??)
},
);
} catch (e) {
print(e);
}
},
),
)),
CodePudding user response:
As I see in your screenshot, the adress
field is not of type array, it's a Map:
So there is no way you can call FieldValue.arrayRemove
. If you want to remove that field, then please use the following lines of code:
Firestore.instance.collection('users').document(data['uid']).set(
{'adress': FieldValue.delete()},
SetOptions(
merge: true,
),
)
Edit:
After you have updated the screenshot, now the adress
field is indeed of type array:
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:
Edit2:
In code it should look like this:
Firestore.instance.collection('users').document(data['uid']).update({
'adress': FieldValue.arrayRemove(elementToDelete),
});
Please note that elementToDelete
object should contain both fields populated. The number
should hold the value of "25" and street
should hold the value of "street A". It will not work if you use only one.
However, if you thought that Firestore provides a direct way to delete an array element by index, please note that is not possible. In such a case, you'll have to read the document, remove the element from the array, then write the document back to Firestore.