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



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

但当我试图在我的应用程序上创建提要/实现全文搜索时,我面临着一个问题。

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

帖子(收藏(->用户ID(文档(->用户帖子(保存所有userID帖子的子集合(->实际帖子(该集合中的单独文档(

我想循环浏览每个用户的用户帖子子集合并获取提要的所有数据,还想用Algolia或ES.等全文搜索应用程序来实现它

  • 我可以循环浏览特定的用户ID(下面的代码(,但作为一个初学者,我找不到一种方法来循环浏览所有用户ID并获取所有用户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-组查询

Algolia实施

您需要使用云函数将字段迁移到专门为Algolia提供的集合中。许多用户发现嵌套子集合在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

如果您只需将帖子提交到主集合,并将userID作为文档中的"所有者"属性,就可以避免上述大多数情况。以上也有好处,但更多的是与博客文章相关的,用户可能会有一个";进行中的工作";版本与Live。

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

最新更新