【发布时间】:2021-05-20 20:08:21
【问题描述】:
我目前正在 Firestore 中创建一个条目,如下所示:
db.collection(userId).document(title).collection(subTitle).addDocument(data: [
"key": "value"
])
我正在获取如下数据。我知道 Firebase 只允许浅层查询,我只想获取即时文档列表(而不是子集合):
self?.db.collection(user!.uid)
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
print("document", document)
document.documents.forEach { (snapshot) in
print("snapshot", snapshot)
let data = snapshot.data()
print("data", data)
}
}
但是,我只从document 得到<FIRQuerySnapshot: 0x7fba4cd2baa0>,没有什么可以解析的。
我也试过了:
self?.db.collection(user!.uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
我得到与上面相同的结果。
但是,当我创建如下条目(没有子集合)时,我可以很好地检索数据:
self.db.collection(userId).document(title).setData([
"key": "value"
])
层次结构
- First collection
- First document
- Second collection
- Second document (with randomly generated ID from "addDocument")
- Fields
令人沮丧的是,即使我按名称引用特定文档,查询返回空:
let docRef = self?.db.collection(user!.uid).document("0x6cac0720c8537467d7d2dccd9b88b8c757e10dfd3dcb8991ff71a4f8dfe1dd")
docRef!.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
【问题讨论】:
-
userId是一个奇怪的集合名称。通常,这将是“用户”集合上的文档名称。共享一个或两个显示在控制台中的层次结构的屏幕图像是值得的。 -
@danh 大部分集合和文档的名称都是动态生成的,但是当我从 Firestore 获取数据时,只获取了硬编码的文档(图中的“result.hash”),这也是没有子集合的那个。另外,我选择
userId作为集合的名称,因为每个用户都会拥有自己的集合。 -
您的文档不存在,这就是您无法阅读任何内容的原因。在屏幕截图中看到下方有“开始收集”和“添加字段”吗?如果您向下滚动(在 Firebase 控制台中),您将看到这条消息此文档不存在,它不会出现在查询或快照中。你知道当它是斜体时文档不存在 - 那只是一个不包含数据的占位符。所以 result.hash 文档确实存在,因为它不是斜体。见This Answer
-
我将此标记为重复,因为问题/问题与链接的问题/答案完全相同。如果不是重复,请提供更多详细信息,我们将取消标记。
-
文档必须包含数据才能存在。文档中的集合不是文档数据,它是一个单独的实体。您所描述的是文档
collection/document/collection中的集合,因此中间的文档只有一个集合,因此它是一个占位符并且不存在。我认为这里存在一个整体设计问题,因为尾随集合(副标题)实际上应该是文档数据。这样做,你说document(title),但这不是标题,它是一个documentID,所以在该文档中添加一个名为title的字段和一些字符串的值
标签: swift firebase google-cloud-firestore