首页 > 解决方案 > 如何在firebase中从一个集合访问另一个集合

问题描述

在此处输入图像描述

如何在 JS v9 中的 firebase 中从一个集合访问另一个集合

标签: javascriptfirebasegoogle-cloud-firestorenosql

解决方案


Firebase 的 JS API v9 带来了不同的变化。最大的变化之一是 DocumentReference 不再允许访问子集合。或者至少,不是直接来自 DocumentReference 本身,我们过去如何使用 v8。

例如,在 v8 中,我们可以这样做:

//say we have a document reference
const myDocument = db.collection("posts").doc(MY_DOC_ID);

//we can access the subcollection from the document reference and, 
//for example, do something with all the documents in the subcollection
myDocument.collection("comments").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        // DO SOMETHING
    });
});

在 v9 中,我们采用了不同的方法。假设我们得到了我们的文档:

const myDocument = doc(db, "posts", MY_DOC_ID);

如您所见,我们编写代码的方式是不同的。在 v8 中,我们曾经以程序化的方式编写它。在 v9 中,一切都切换到了更实用的方式,我们可以使用诸如 doc()、collection() 等函数。因此,为了与上面的示例做同样的事情并对子集合中的每个文档做一些事情,v9 API 的代码应该如下所示:

const subcollectionSnapshot = await getDocs(collection(db, "posts", MY_DOC_ID, "comments"));
subcollectionSnapshot.forEach((doc) => {
  // DO SOMETHING
});

请注意,我们可以将其他参数传递给诸如 collection() 和 doc() 之类的函数。第一个将始终是对数据库的引用,第二个将是根集合,从那里开始,每个其他参数都将添加到路径中。在我的例子中,我写的地方

collection(db, "posts", MY_DOC_ID, "comments")

它的意思是

  • 进入“帖子”集合
  • 选择 id 等于 MY_DOC_ID 的文档
  • 进入该文档的“评论”子集合

推荐阅读