[英]Firestore how to store reference to document / how to retrieve it?
I am new to Firestore/Firebase and I am trying to create a new document with one of the fields being a document reference
to an other document. 我是Firestore / Firebase的新手,我正在尝试创建一个新文档,其中一个字段是对其他文档的
document reference
。 I have read all the guides and examples from Firebase and did not find anything... 我已经阅读了Firebase的所有指南和示例,但没有找到任何内容......
Also, when I retrieve this document I created, I would be able to access what is inside the reference I added inside. 此外,当我检索我创建的这个文档时,我将能够访问我在里面添加的引用内容。 I have no idea how to do that.
我不知道该怎么做。
Here is some code I tried for the creating part 这是我为创建部分尝试的一些代码
let db = Firestore.firestore()
// Is this how you create a reference ??
let userRef = db.collection("users").document(documentId)
db.collection("publications").document().setData([
"author": userRef,
"content": self.uploadedImagesURLs
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
You're just missing one step. 你只是错过了一步。 This took me a while to figure out as well.
我花了一段时间才弄明白。
First, store a variable DocumentReference! 首先,存储一个变量DocumentReference!
var userRef: DocumentReference!
Then, you want to create a pointer to the document ID — create a DocumentReference from that <- this part you are missing 然后,您想要创建一个指向文档ID的指针 - 从那个< - 这个缺少的部分创建一个DocumentReference
if let documentRefString = db.collection("users").document(documentId) {
self.userRef = db.document("users/\(documentRefString)")
}
Finally, resume saving your data to the database 最后,继续将数据保存到数据库
db.collection("publications").document().setData([
"author": userRef,
"content": self.uploadedImagesURLs
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
Hope that helps! 希望有所帮助!
This way works perfectly for me: 这种方式适合我:
let db = Firestore.firestore()
let documentRefString = db.collection("users").document(documentID)
let userRef = db.document(documentRefString.path)
Then, when you will set the data: 然后,当您设置数据时:
db.collection("publications").document().setData([
"author": userRef,
"content": self.uploadedImagesURLs
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.