Firestore how to store reference to document / how to retrieve it?
12,313
You're just missing one step. This took me a while to figure out as well.
First, store a variable 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
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!
Related videos on Youtube
Comments
-
Scaraux almost 2 years
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. I have read all the guides and examples from Firebase and did not find anything...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!") } }
-
Doug Stevenson about 6 yearsWhen you read the document and get the
author
field, it should be a document reference just like the one you first put in there. -
Scaraux about 6 yearsSo is what I did the proper way to store a reference ? And when I get this same field, it is actually a
Any
type. I tried to cast it without success. What method should I call on the field once I get it, to access the actual document it points to?
-