简体   繁体   English

如何在 Swift 中没有 documentID 的情况下在 firestore 中获取子集合?

[英]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:我想访问 firestore 数据库中用户数据文档的视频子集合部分:

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.这将是我将使用的方法,但我不打算使用 documentID,因此我必须首先通过使用 whereField() 方法的查询来访问特定文档。 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.此外,我最终得到了一个 QueryDocumentSnapShot,我还需要对其进行转换,以便能够访问其中包含的子集合。 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.此外,我特别不想使用 documentID,因为我将 Firestore 设置为为我的文档生成 AutoID 以提高安全性。 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.例如,您可以使用 where() 查询所有满足特定条件的文档,然后使用 get() 检索结果,这是您已知的解决方案。 I don't think there will be a better solution than this.我认为没有比这更好的解决方案了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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