Cloud Firestore Swift:如何删除文档查询 [英] Cloud Firestore Swift: How to delete a query of documents
问题描述
我想删除我的集合用户名中所有具有UID字段作为当前用户ID的文档.到目前为止,这是我的代码:
I would like to delete all documents in my collection Usernames that has the field UID as the current user's ID. This is my code so far:
let uid = Auth.auth().currentUser!.uid
db.collection("Usernames").whereField("UID", isEqualTo: uid).delete
但是出现错误:
查询"类型的值没有成员删除".
Value of type 'Query' has no member 'delete'.
有什么特殊的技巧吗?谢谢!
Any special technique to this? Thanks!
推荐答案
指南介绍了如何删除数据.它还指出,不应从客户端删除整个集合.无法从查询中删除-您将必须获取所有文档并分别删除它们.如果存在大量文档的可能性,则应在服务器端进行操作.如果您确定只有少数几个,则可以查询它们,获取文档引用,然后删除它们,如下所示:
The guide shows you how to delete data. It also notes that deleting entire collections shouldn't be done from the client. There's no way to delete from a query -- you will have to get all the documents and delete them individually. If there is the potential for lots of documents, then you should do this server-side. If you know for sure there will only be a few, you can query them, get the doc references, and then delete them, like this:
let uid = Auth.auth().currentUser!.uid
db.collection("Usernames").whereField("UID", isEqualTo: uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
document.reference.delete()
}
}
}
如果这是需要经常执行的操作,那么这是检查您的数据结构的好机会.也许进行一个收集,其中用户的用户名列在其uid
下.然后,您可以查询单个文档,并使用它引用要删除的其他文档.
If this is something that will need to be done frequently, then this is a good opportunity to examine your data structure. Maybe make a collection where user's Usernames are listed under their uid
. Then you could just query that single doc and use it to reference the other ones to delete.
Usernames: {
byUID: {
uid1: {
funky_monkey: true,
goodTimes: true
}
}
byUsername: {
funky_monkey: {
UID: uid1
}
}
}
这只是一个建议.肯定还有其他选项可能更适合您的应用程序.
This is just one suggestion. There are definitely other options that may be better for your app.
这篇关于Cloud Firestore Swift:如何删除文档查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!