[英]Nested Struct with Document Reference in Swift Firestore
I have a Book model looking like this:我有一本书 model 看起来像这样:
struct Book: Identifiable {
var id = UUID().uuidString
var text: String
var styleReference: DocumentReference
var style: BookStyle //not in the Firestore Document
}
with the style looking like this:样式如下:
struct BookStyle: Identifiable {
var id = UUID().uuidString
var imageUrlString: String
var fontString: String
}
This is what my Firestore Book model looks like:这是我的 Firestore Book model 的样子:
I can fetch the Books like this:我可以这样取书:
func fetchData() {
db.collection("books").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else { return }
self.books = documents.compactMap { queryDocumentSnapshot -> Book? in
return try? queryDocumentSnapshot.data(as: Book.self)
}
}
}
My problem now is: Where should I get the BookStyle Data?我现在的问题是:我应该从哪里获得 BookStyle 数据? I have the reference to the document but I don't know where to fetch and assign it.
我有对文档的引用,但我不知道在哪里获取和分配它。
you could try something like this (totally untested), with var style: BookStyle?
你可以尝试这样的事情(完全未经测试),使用
var style: BookStyle?
and a loop over the books:和书籍循环:
func fetchData() {
db.collection("books").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else { return }
self.books = documents.compactMap { queryDocumentSnapshot -> Book? in
return try? queryDocumentSnapshot.data(as: Book.self)
}
// -- here
for i in self.books.indices {
db.document(self.books[i].styleReference).getDocument { (snapshot, error) in
let bookStyle = snapshot.compactMap { queryDocumentSnapshot -> BookStyle? in
return try? queryDocumentSnapshot.data(as: BookStyle.self)
}
self.books[i].style = bookStyle
}
}
}
}
}
struct Book: Identifiable {
let id = UUID().uuidString
var text: String
var styleReference: DocumentReference
var style: BookStyle? // <-- here optional
}
struct BookStyle: Identifiable {
let id = UUID().uuidString
var imageUrlString: String
var fontString: String
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.