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")
它的意思是
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句