如何从一个集合访问 firebase 中的另一个集合
How to get access from one collection to another collection in firebase
如何在 JS v9 的 firebase 中从一个集合访问另一个集合
Firebase 的 JS API v9 带来了不同的变化。
最大的变化之一是 DocumentReference 不再允许访问 subcollections。或者至少,不是直接来自 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() 等函数。
所以,为了做我们在上面的例子中所做的同样的事情,并且对子 collection 中的每个文档做一些事情,v9 API 的代码应该如下所示:
const subcollectionSnapshot = await getDocs(collection(db, "posts", MY_DOC_ID, "comments"));
subcollectionSnapshot.forEach((doc) => {
// DO SOMETHING
});
请注意,我们可以将其他参数传递给 collection() 和 doc() 等函数。第一个将始终是对数据库的引用,第二个将是根 collection 并且从那里开始,每个其他参数都将添加到路径中。在我的示例中,我写了
collection(db, "posts", MY_DOC_ID, "comments")
意思是
- 进入“帖子”collection
- 选择 id 等于 MY_DOC_ID
的文档
- 进入该文档的“评论”子collection
如何在 JS v9 的 firebase 中从一个集合访问另一个集合
Firebase 的 JS API v9 带来了不同的变化。 最大的变化之一是 DocumentReference 不再允许访问 subcollections。或者至少,不是直接来自 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() 等函数。 所以,为了做我们在上面的例子中所做的同样的事情,并且对子 collection 中的每个文档做一些事情,v9 API 的代码应该如下所示:
const subcollectionSnapshot = await getDocs(collection(db, "posts", MY_DOC_ID, "comments"));
subcollectionSnapshot.forEach((doc) => {
// DO SOMETHING
});
请注意,我们可以将其他参数传递给 collection() 和 doc() 等函数。第一个将始终是对数据库的引用,第二个将是根 collection 并且从那里开始,每个其他参数都将添加到路径中。在我的示例中,我写了
collection(db, "posts", MY_DOC_ID, "comments")
意思是
- 进入“帖子”collection
- 选择 id 等于 MY_DOC_ID 的文档
- 进入该文档的“评论”子collection