简体   繁体   English

如何从 swift 的 Firebase Firestore 中删除当前用户的特定文档?

[英]How to delete specific document for the current user from Firebase Firestore in swift?

I'm using Firebase Firestore to store collection of tasks.我正在使用 Firebase Firestore 来存储任务集合。
I want to create following scenario: when user deletes a specific task, it should be removed from tableview and from database only for this current user.我想创建以下场景:当用户删除特定任务时,它应该从 tableview 和数据库中删除,仅针对当前用户。 But I'm only able to delete the selected task from db at all, not for current user.但我只能从数据库中删除选定的任务,而不是当前用户。 Please help!请帮忙!

My set up code:我的设置代码:

class TasksListScreen: UIViewController {
    var tasksArray = [Task]() // array of tasks via Task struct

    // to load data from db
    func loadData() {
        db.collection("tasks").getDocuments { (queryShapshot, error) in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                self.tasksArray = queryShapshot!.documents.flatMap({Task(dictionary: $0.data())})
                // to update user interface
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

I'm able to delete selected task (document) from my collection at all via this code.我可以通过此代码从我的集合中删除选定的任务(文档)。

extension TasksListScreen: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        // if action is deletion
        if editingStyle == UITableViewCell.EditingStyle.delete {

            let title = tasksArray[indexPath.row].title
            let collectionRef = db.collection("tasks")
            let query : Query = collectionRef.whereField("title", isEqualTo: title)

            query.getDocuments(completion:{ (snapshot, error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    for document in snapshot!.documents {
                        self.db.collection("tasks").document("\(document.documentID)").delete()
                    }
                }
            })

            // delete task from table view
            tasksArray.remove(at: indexPath.row)
            //tableView.reloadData()
            tableView.deleteRows(at: [indexPath], with: .fade)
        }
}

But I need to delete selected document from db only for the current user.但我只需要为当前用户从数据库中删除选定的文档。 I've tried this code.我试过这段代码。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        // if action is deletion
        if editingStyle == UITableViewCell.EditingStyle.delete {

            // delete task from db for the current user
            let title = tasksArray[indexPath.row].title
            let user = Auth.auth().currentUser
            // access collection of tasks of the current user
            let collectionRef = db.collection("users").document((user?.uid)!).collection("tasks")
            // search for task with needed title
            let query : Query = collectionRef.whereField("title", isEqualTo: title)
            print(title)
            print(query)
            query.getDocuments(completion:{ (snapshot, error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    for document in snapshot!.documents {
                        self.db.collection("users").document((user?.uid)!).collection("tasks").document("\(document.documentID)").delete()
                    }
                }
            })
        }
 }

It deletes task during the current session, but when I run my app again the deleted task appears.它会在当前 session 期间删除任务,但是当我再次运行我的应用程序时,会出现已删除的任务。

Please help!请帮忙!

If the document has a field that contains the userId, you can do something like this:如果文档有一个包含 userId 的字段,您可以执行以下操作:

for document in snapshot!.documents {
     if document.userId == user.userId {
         self.db.collection("tasks").document("\(document.documentID)").delete()
}
               }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM