【问题标题】:Swift cannot convert value of type 'Query' to expected argument type 'DocumentReference'Swift 无法将“Query”类型的值转换为预期的参数类型“DocumentReference”
【发布时间】:2020-11-23 09:06:03
【问题描述】:

基本上,我要做的是,一旦点击 postTaskButton,将信息从 titleTextField 复制到“prtasks”集合中的新文档,然后将其复制到当前登录用户的个人文档中“用户”集合。

为此,我尝试在点击“PostTasks”按钮后执行批量写入。但是,Xcode 以粗体显示错误“无法将 'Query' 类型的值转换为预期的参数类型 'DocumentReference'”。

    @IBAction func postTaskButton(_ sender: Any) {
    
    let title = titleTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let db = Firestore.firestore()
    let batch = db.batch()
    
    //Copy the information from the form to the 'prtasks' root collection
    let prtasksRef = db.collection("prtasks").document()
    batch.setData(["title" : title], forDocument: prtasksRef)
    
    //Copy the information from the form to a map entry in the user's personal tasks collection
    let userTasksRef = db.collection("users").whereField("uid", isEqualTo: Auth.auth().currentUser?.uid ?? "")
    **batch.setData(["title": title], forDocument: userTasksRef)**

    //Commit all of the above batch writes to the firestore
    batch.commit() { (error) in
        if error != nil {
            self.showAlert(for: "Error Writing Batch")
        } else {
            self.showAlert(for: "Batch write succeeded.")
        }
    }

}

【问题讨论】:

    标签: swift database firebase google-cloud-firestore


    【解决方案1】:

    Firestore 不支持更新查询的概念,您可以将条件和要更新的数据发送到服务器。只有知道文档的确切/完整路径时,才能写入文档。

    这意味着您必须:

    1. 执行查询以获取匹配的文档。
    2. 循环匹配的文档。
    3. 依次(或批量)更新每个文档。

    由于我注意到您正在查询一个名为 users 的集合:使用用户 UID 作为文档 ID 来存储配置文件文档更为常见。通过这样做,您无需执行查询来更新用户文档,而是可以执行以下操作:

    let userDocRef = db.collection("users").doc(Auth.auth().currentUser!.uid)
    batch.setData(["title": title], forDocument: userDocRef)
    

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多