Is there a way to remove key-value pair on firestore?
method of setData() or updateData() doesn't work for me as I don't want to set or update I just want to remove that pair.
in realtime database (old version of firestore) we were able to do that like this:
FIRDatabase.database().reference().child("following").child(currentUserId).child(userId).removeValue()
what is equivalent for this on firestore? what we can use instead of removeValue() method?
I try to find a solution for deleting key-value pair on firebase's firestore but I have not found a solution anywhere. I read the document of firestore and all of old questions in here, however I have not even found any approachment.
this is my firestore structure
let firestoreDatabase = Firestore.firestore()
firestoreDatabase.collection("following").whereField("\(userId)", isEqualTo: 1).addSnapshotListener { snapshot, error in
if error != nil {
print(error?.localizedDescription ?? "error")
}else {
if snapshot?.isEmpty != true && snapshot != nil {
DispatchQueue.global().async {
for document in snapshot!.documents {
if document.exists && document.reference.documentID == cuid {
document.reference. ??? // what should we going to do?
}
}
}
}
}
}
}
this is how I tried to find a solution. but I am open to different approachments or mindsets. I don't know that I try to right way.
anyway, how can we remove that pair?
CodePudding user response:
To delete a field from a document, mark it with FieldValue.delete()
in a write operation. See this code sample from the documentation on deleting fields:
db.collection("cities").document("BJ").updateData([
"capital": FieldValue.delete(),
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
You can call updateData
on your document.reference.
object and pass FieldValue.delete()
for the field you want to delete.
The way you load the documents seems overly complex. If you know the document ID of the document you want to remove the field from, it should be something like this:
firestoreDatabase.collection("following").document(cuid).updateData([
"nameOfFieldToRemove": FieldValue.delete(),
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}