okay so what i am trying to achieve is delete the marked data when the elevated button is pressed here is the image data inside firestore,
here is my code to upload data, its map right ?
// setting received_request
final data_2 = {
"received_request" : FieldValue.arrayUnion([{
"sender" : args.user_uid,
"receiver" : args.uid,
"Name" : args.name_of,
"status" : "pending",
"details" : {
"date" : detail_class.datetime,
"total_dishes" : detail_class.total_dishes,
"total_people" : detail_class.total_people,
"meals" : detail_class.meals,
"location" : detail_class.location,
"info" : detail_class.info,
}
}]),
};
// sending received_request to the database
db.collection("users").doc(args.uid).set(data_2, SetOptions(merge: true));
now what i want to achieve is delete the first index 0 when the user presses a button,
i have searched a lot and got to know that its possible through this FieldValue.arrayRemove()
now i have given FieldValue.arrayRemove() everyfield present inside the data but in vain,
i am lost at this point sorry my data structures are not great .
// delete it
var collection = FirebaseFirestore.instance.collection('users');
collection
.doc(loggedInUser.uid)
.update( {
'received_request': FieldValue.arrayRemove([{
"sender" : '${snapshot.data[0]['received_request'][index] ['sender']}', "receiver":'${snapshot.data[0]['received_request'][index ['receiver']}',
"Name" : '${snapshot.data[0]['received_request'][index]['Name']}',
"status" : '${snapshot.data[0]['received_request'][index]['status']}',
"details" : {
"date":'${snapshot.data[0]['received_request'][index]['details']['date']}',
"total_dishes":'${snapshot.data[0]['received_request'][index]['details']['total_dishes']}',
"total_people":'${snapshot.data[0]['received_request'][index]['details']['total_people']}',
"meals":'${snapshot.data[0]['received_request'][index]['details']['meals']}',
"location":'${snapshot.data[0]['received_request'][index]['details']['location']}',
"info": '${snapshot.data[0]['received_request'][index]['details']['info']}',
}
}]),
}
);
2
Answers
You need to use
set
withSetOptions(merge: true)
when you delete, otherwise all other fields will be removed.I also think that you don’t have to repeat the entire map.
So try this:
Yes, that is correct. You can use
FieldValue.arrayRemove()
to remove a specific object from within an array. Your object wasn’t removed because most likely you didn’t pass an object which is the same as the one in the array. To have a match, the object that you pass, it’s mandatory to have the exact fields and the exact values as the object in the database. It will not work with partial data or different data.On the other hand, there is no way you can delete an element at a specific index in an array unless you read the document, delete the object from the array, and then write the document back to Firestore.