BubH
BubH

Reputation: 67

Firebase SwiftUI - Create document with subcollection

I am trying to add a comment's feature to my app. When a user creates a post, I am trying to also add a sub-collection to that post names "comments". However, with the code I have, I simply can not figure out how to create this sub-collection. Preferably, I would like to create this sub-collection with no documents inside by default, however I've read that thats not possible.

if img_Data.count == 0{
            
            ref.collection("Posts").document().setData([
                "title" : self.postTxt,
                "url": "",
                "ref": ref.collection("Users").document(self.uid),
                "time": Date(),
                "likes": 0,
                "likedBy": FieldValue.arrayUnion([])
            ])
            ref.collection("Posts").document().collection("comments").document().setData([ //this is where I am trying to create "comments" but it's not working.
                "title": "testing"
            ])
            { (err) in
                
                if err != nil{
                    self.isPosting = false
                    return
                }
                
                self.isPosting = false
                //closing view when posted
                present.wrappedValue.dismiss()
            }
        }
///else statement for image posting

The code above does not create a sub-collection with the new post.

I BELIEVE my problem is under ".document().collection("comments"). I don't have anything inside the (), so it's unsure what document to add the sub-collection to. In my other files, I've simply referenced "id" for a specific document, but I am not sure how to do that since I am creating the document as-well as then modifying it.

If there is a better way to do this, please let me know. This is what I came up with.

Upvotes: 1

Views: 826

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598775

When you call document() on a collection reference, it returns a new document reference. If you capture that reference in a variable, you can create the new subcollection under that specific document.

So:

let newDocRef = ref.collection("Posts").document()     // 👈 Capture new document reference
newDocRef.setData([                                    // 👈 Create the new document itself
    "title" : self.postTxt,
    "url": "",
    "ref": ref.collection("Users").document(self.uid),
    "time": Date(),
    "likes": 0,
    "likedBy": FieldValue.arrayUnion([])
])
newDocRev.collection("comments").document().setData([  // 👈 Create a document in the subcollection
    "title": "testing"
])

Upvotes: 3

Related Questions