如何访问 Firestore 中查询文档的子集合?

Pau*_*ina 4 javascript firebase google-cloud-firestore

上下文:以下是我在 Firebase Firestore 中的集合和文档的屏幕截图。基本上,每个交易文档都有自己的字段和其中的聊天集合。

我需要什么:我的目标是使用特定的 handler_id 查询文档并访问其中的聊天集合。

发生了什么:此查询仅返回交易字段

 db.collection("transaction").where("handler_id", "==", 3)
Run Code Online (Sandbox Code Playgroud)

如何在查询的文档中包含聊天集合?您对我如何更有效地构建数据有什么建议吗? 在此处输入图片说明

Ren*_*nec 7

Firestore 中的查询是浅层的,这意味着当您通过查询查询文档时,您只会获得您正在查询的集合中的相应文档,而不是其子集合中的文档。

所以需要先查询父transaction文档(也是一个异步过程),拿到之后再查询子集合(也是一个异步过程)。

如果我们假设transaction集合中只有一个带有 的文档handler_id = 3,您将按照以下方式进行操作:

db.collection("transaction").where("handler_id", "==", 3).get()
.then(querySnapshot => {
   return querySnapshot.docs[0].ref.collection('chat').get();
})
.then(querySnapshot => {
    querySnapshot.forEach(doc => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});
Run Code Online (Sandbox Code Playgroud)

如果你想为chat子集合设置一个监听器,你只需要调用onSnapshot()方法而不是方法get(),如下所示:

db.collection("transaction").where("handler_id", "==", 3).get()
.then(querySnapshot => {
   querySnapshot.docs[0].ref.collection('chat').onSnapshot(querySnapshot => {
        // Do whatever you want with the querySnapshot
        // E.g. querySnapshot.forEach(doc => {...})
        // or querySnapshot.docChanges().forEach(change => {...})
        // See https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection
    });
}); 
Run Code Online (Sandbox Code Playgroud)