javascript - 如何在firebase中从一个集合访问另一个集合
解决方案
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 的文档
- 进入该文档的“评论”子集合
推荐阅读
- azure - 使用 Azure CLI 更新 EventGrid 主题以设置 DeadLettering 目标
- jakarta-ee - 由于未定义的组件类型 jakarta.faces.ViewRoot,在 TOMEE-9.0 PLUS 上运行简单的 JSF webapp 无法正常启动
- javascript - 未找到括号内的空格 Prettier
- arrays - 如何按值减少对象数组
- javascript - 有什么办法可以暂停所有的事件监听器?
- android - 谷歌通常需要多长时间来审查封闭测试中的应用程序?
- cygwin - 在 Cygwin (Windows 10) 中使用气候数据运算符 (CDO) 的日常异常
- facebook - 您能否针对非网络 Facebook Conversions API 事件进行优化?
- caching - Cloudflare 兑现一切
- android - 如何让 MotionLayout 上的 AnimateLayoutChanges 正常工作?