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!")
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With