如果集合包含具有用户 id 的文档,如何返回包含集合的文档

问题描述 投票:0回答:2

我在 Firebase 中有一个帖子集合,其中包含人们在我的应用程序上发布的所有帖子,每个文档都有自己的“帖子保存”和“帖子喜欢”集合。当用户保存帖子时,会将其用户 ID 添加到帖子内的“保存后”集合中。我想创建一个查询来查找“post-saves”集合中具有用户 id 的所有帖子,然后返回帖子数据,但用户的 id 是“post-saves”集合中的文档,它只是返回用户的 ID。

static func FetchUserSavedPosts(uid: String) async throws -> [Post] {

    let docsnapshot = try await postsCollection.document().collection("post-saves").whereField("userid", isEqualTo: uid).getDocuments()
        return try docsnapshot.documents.compactMap({ try $0.data(as: Post.self) })
    
}

static func checkIfUsersavedPost(_ post: Post) async throws -> Bool {
    guard let uid = Auth.auth().currentUser?.uid else { return false }

    let snapshots = try await
    postsCollection.document(post.id).collection("post-saves").document(uid).getDocument()
    return snapshots.exists
}

//save post

static func savepost(_ post: Post) async throws {
    guard let uid = Auth.auth().currentUser?.uid else { return }
            
    let postRef = postsCollection.document(post.id).collection("post-saves").document(uid)
    
    let post = UserID(id: uid)
    
    guard let encodedPost = try? Firestore.Encoder().encode(post) else { return }
    
    async let _ = try await postRef.setData(encodedPost)
}
}

datastructure image

如果您需要更多详细信息/清晰度,请告诉我。

ios swift firebase google-cloud-platform google-cloud-firestore
2个回答
0
投票

您正在获取嵌套集合的快照

post-saves
。您是否尝试使用过滤器通过
posts
进行查询,如下所示:

let docsnapshot = try await postsCollection.document().collection("posts").whereField("post-saves.userid", isEqualTo: uid).getDocuments()

0
投票

当您使用以下查询时:

postsCollection.document().collection("post-saves").whereField("userid", isEqualTo: uid)
//                      👆

这意味着您正在尝试获取

post-saves
子集合中的所有文档,其中
userid
字段保存 UID 值,很可能是经过身份验证的用户。

在上面的代码中,当您没有将 ID 传递给

.document()
函数时,这意味着您正在生成一个全新的文档 ID,而不是使用集合中存在的文档 ID。如果你想创建这样的引用,你必须传递文档的 ID,如下所示:

postsCollection.document("3iKc...G2o3").collection("post-saves").whereField("userid", isEqualTo: uid)
//                      👆

要获取突出显示文档的内容,如果您已经拥有该 ID,则没有理由使用查询。您可以使用以下文档参考轻松阅读该文档:

postsCollection.document("3iKc...G2o3").collection("post-saves").document("Puut...rM23")

因此需要两个 ID 来创建引用。如果子集合中有多个文档,那么确实需要查询。但请记住,子集合内的文档应包含一个保存该 UID 的字段:

postsCollection.document("3iKc...G2o3").collection("post-saves").whereField("userid", isEqualTo: uid)
© www.soinside.com 2019 - 2024. All rights reserved.