从多个子集合中获取文档 – Firebase

huangapple go评论72阅读模式
英文:

Fetch documents from multiple subcollections - Firebase

问题

我正在创建一个与Firebase集成的管理员Web应用程序,该Web应用程序由管理员使用,用于监视由Android或iOS应用程序中的用户发布的帖子或评论。

我正在使用Firebase Firestore,并且以下是数据库设计:
posts/{postsDocument}/comments/{commentsDocument}

这里的commentspostsDocument的子集合,它保存了特定帖子的所有评论。此外,postDocumentcommentsDocument包含了用户的Firebase uid。

我的问题是,是否有可能获取特定用户评论的所有评论。我可以查询单个集合,但在这种情况下,commentsDocument是一个子集合,我希望获取用户在监视目的下对所有帖子的所有评论。

英文:

I'm creating a web app for admin with firebase integration, this web app is used by admin to monitor posts or comments posted by user from Android or iOS app developed in ionic.

I'm using Firebase firestore, and following is the database design
posts/{postsDocument}/comments/{commentsDocument}.

The comments here is sub-collection for postsDocument that holds all the comments for a particular post. Also postDocument and commentsDocument contains Firebase uid of the user.

My problem is, whether it's possible to fetch all the comments commented by a particular user. I can query a single collection, but in this scenario commentsDocument is a subcollection and i want to fetch all comments across all the post by a user for monitoring purpose.

答案1

得分: 2

你可以查看 Firebase 集合组查询

var commentsQuery = db.collectionGroup('comments').where('commentOwnerID', '==', userId); //userId - 用户评论的 Firebase ID
commentsQuery.get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
        console.log(doc.id, ' => ', doc.data());
    });
});

另外,您可能需要创建支持您的查询的索引,请查看控制台以获取创建索引的链接。

英文:

You can check firebase collection group query

var commentsQuery = db.collectionGroup('comments').where('commentOwnerID', '==', userId);//userId - firebase id of the user who commented
commentsQuery.get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
        console.log(doc.id, ' => ', doc.data());
    });
});

Also you might have to create index that supports your query, check console for the the link for creating index

huangapple
  • 本文由 发表于 2020年1月6日 19:46:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定