简体   繁体   中英

How to fetch subcollections in firestore without documentID in Swift?

I want to access a video subcollection part of my user's data document in the firestore database:

func fetchRecentVideos(ofArtist artistName: String) async -> [VideoModel] {
        let usersRef = db.collection("users")
        let userDocs = try! await usersRef.whereField("artistName", isEqualTo: artistName).getDocuments()
        
        if userDocs.count != 1 {
            print("snapshot.count was not 1!!!!")
        }
        
        userDocs.documents[0].collection("videos")
        
    }

I've seen plenty of posts and documentations showing how you can access subcollections by explicitly stating the path to the subcollection as such:

db.collection("users/\(documentIDofInterest)/videos") 

This would've been the approach I'd use but I don't intend to use the documentID, so I must access the particular document first through a query using the whereField() method. However, this quickly is getting verbose. Also, I end up with a QueryDocumentSnapShot and I further need to transform it to be able to access the subcollection contained within it. Is there a simpler way I'm missing?

Also, I specifically don't want to use the documentID because I set Firestore to generate an AutoID for my documents for better security. But, as a consequence of that, am I making things difficult by doing that? Should I then rename my documents with perhaps the usernames or something similar?

As per the documentation , which is clearly mentioned You can retrieve documents with one request by querying documents in a collection. For example, you can use where() to query for all of the documents that meet a certain condition, then use get() to retrieve the results which is the known solution for you. I don't think there will be a better solution than this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM