[英]how to delete key-value pair on firestore? (not just value or key both of them)
有没有办法删除 firestore 上的键值对?
setData() 或 updateData() 的方法对我不起作用,因为我不想设置或更新我只想删除那对。
在实时数据库(旧版本的 firestore)中,我们可以这样做:
FIRDatabase.database().reference().child("following").child(currentUserId).child(userId).removeValue()
这在 Firestore 上有什么等价物? 我们可以使用什么来代替 removeValue() 方法?
我试图在 firebase 的 firestore 上找到删除键值对的解决方案,但我没有在任何地方找到解决方案。 我在这里阅读了 firestore 的文档和所有旧问题,但我什至没有找到任何方法。
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?
}
}
}
}
}
}
}
这就是我试图找到解决方案的方式。 但我对不同的方法或心态持开放态度。 我不知道我试图以正确的方式。
无论如何,我们怎样才能删除那对呢?
要从文档中删除字段,请在写入操作中用FieldValue.delete()
标记它。 请参阅有关删除字段的文档中的此代码示例:
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")
}
}
您可以在document.reference.
上调用updateData
。 对象并为要删除的字段传递FieldValue.delete()
。
您加载文档的方式似乎过于复杂。 如果您知道要从中删除该字段的文档的文档 ID,它应该是这样的:
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")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.