繁体   English   中英

查询集合中的所有文档,以及 firestore 中的所有子集合

[英]Query through all documents in a collection, and through all subcollections in firestore

我正在使用 Firebase Firestore 作为 BaaS 构建一个应用程序。

但是当我尝试在我的应用程序上创建提要/实现全文搜索时,我遇到了一个问题。

我希望能够搜索所有用户帖子,问题是,用户帖子在 Firestore 数据库中的结构如下:

帖子(集合)-> 用户 ID(文档)-> 用户帖子(包含所有用户 ID 帖子的子集合)-> 实际帖子(该集合中的单独文档)

我想遍历每个用户的用户帖子子集合并获取提要的所有数据,并使用像 Algolia 或 ES 这样的全文搜索应用程序来实现它。

  • 我可以遍历一个特定的用户 ID(下面的代码),但是作为一个初学者,我找不到一种方法来遍历所有这些并获取所有这些。

     firebase.firestore() .collection('allPosts') .doc('SPECIFIC_USER_ID') //-> Here I have to loop through all docs in that collection .collection('userPosts') .orderBy("creation", "asc") .get() .then((snapshot) => { let posts = snapshot.docs.map(doc => { const data = doc.data(); const id = doc.id; return { id, ...data } }) setUserPosts(posts) }) }

希望得到一些帮助!

集合组查询

您可以使用集合组查询在所有名为 X 的集合中进行查询。

var posts= db.collectionGroup('userPosts').orderBy('creation').limit(10);
posts.get().then((querySnapshot) => {
              let posts = querySnapshot.map(doc => {
                  const data = doc.data();
                  const id = doc.id;
                  return { id, ...data }
              })
              setUserPosts(posts)
});

来源: https : //firebase.google.com/docs/firestore/query-data/queries#collection-group-query

阿尔戈利亚实施

您将需要使用 Cloud Functions 将字段迁移到专门用于 Algolia 的专用集合。 许多用户发现嵌套的 SubCollections 在 Algolia 的设置中存在问题。 为此,您可以将用户 Post 数据作为“来源”复制到这个新的公共集合中,并使用 Firebase Algolia 扩展,您可以直接同步它

exports.bakePosts= functions.firestore
    .document('allPosts/{userID}/userPosts/{postID}')
    .onWrite((change, context) => {
      // Get an object with the current document value.
      // If the document does not exist, it has been deleted.
      const document = change.after.exists ? change.after.data() : null;

      // Get an object with the previous document value (for update or delete)
      const oldDocument = change.before.data();
      if(document != null)
          db.collection("posts/"+ context.params.postID).set(document);
      if(document == null)
          db.collection("posts/"+ context.params.postID).delete();
    });

Algolia 扩展: https ://firebase.google.com/products/extensions/firestore-algolia-search

如果您只是将帖子提交到主集合并且将用户 ID 作为文档中的“所有者”属性,则可以避免上述大部分情况。 以上也有好处,但更多与博客文章相关,其中用户可能有一个“正在进行的”版本与 Live。

Algolia 扩展有关于如何设置它的完整指南,如果您需要自定义扩展,源代码也可用。

暂无
暂无

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

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