Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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!")
        }
    }
like image 745
Scaraux Avatar asked Apr 25 '18 01:04

Scaraux


1 Answers

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!

like image 144
wheelerscott Avatar answered Oct 22 '22 02:10

wheelerscott