Swift Firestore 获取文档ID

3

我正在使用FirebaseFirestore作为我的数据库。

我有一个包含名称和描述的列表数组。我也想获取每个列表的唯一文档ID。这是可能的吗?

List.swift

struct List {
    var name:String
    var description:String

    var dictionary:[String:Any] {
        return [
            "name":name,
            "description":description
        ]
    }
}

ListTableViewController.swift

func getLists() {
    if Auth.auth().currentUser != nil {
        db.collection("lists").getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                self.listArray = querySnapshot!.documents.flatMap({List(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

我发现你可以通过以下方式获取文档的ID...

    for document in querySnapshot!.documents {
        print("\(document.documentID) => \(document.data())")
    }

但是,我该如何将这个存储在我的列表中以便以后调用呢?
3个回答

9

1. 假设您正在获取快照中的文档。

    guard let documents = ducomentSnapshot?.documents else {
      print("Error fetching documents: \(error!)")
      return
   }

//使用此代码获取每个文档对象的documentId。

  for i in 0 ..< documents.count {
        let dictData = documents[i].data()
        let documentID = documents[i].documentID
        print("Document ID \(documentID)")
    }

0

我不确定这是否是最好的方法,但我将其附加到listArray中,似乎可以工作。

self.listArray.append(List(name: document["name"] as! String, description: document["description"] as! String, documentId: document.documentID))

0
在你的列表结构中添加一个id属性:
struct List {
    var name:String
    var description:String
    var id: String?

    var dictionary:[String:Any] {
        return [
            "name":name,
            "description":description
        ]
    }
}

接着当手动映射文档时,需分配id属性:

list = documents.compactMap{ (queryDocumentSnapshot) -> List? in
    var listItem = try? queryDocumentSnapshot.data(as: List.self)
    listItem?.id = queryDocumentSnapshot.documentID
    return listItem
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接