如何在Firestore Web版本9(模块化)中获得集合中的子集合?



我正在使用Firestore Web 8的链接模式,但我正在将其更新到模块9,并且很难弄清楚如何获得我的子集合(集合内的集合)的所有内容。
我的旧函数是这样的,工作正常:

function getInfo(doc_name) {
let infoDB = db
.collection("collection_name")
.doc(doc_name)
.collection("subcollection_name")
.get();
return alunoHistorico;
}

用模块方式,我试过这个代码

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const docRef = doc(db, "collection_name", "doc_name");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}

但是函数doc()期望一个偶数参数(不包括db参数),所以如果我尝试使用3个这样的参数,我会得到一个错误:

const docRef = doc(db, "collection_name", "doc_name", "subcollection_name");

要让它工作,我必须传递子集合

中的文档
const docRef = doc(db, "collection_name", "doc_name", "subcollection_name", "sub_doc");

,但它不适合我,因为我有一个列表的文档在子集合中,我想检索。如何将所有文档放到子集合中呢?

感谢所有花时间的人。

您需要使用collection()来获得CollectionReference而不是返回DocumentReferencedoc():

const subColRef = collection(db, "collection_name", "doc_name", "subcollection_name");
// odd number of path segments to get a CollectionReference
// equivalent to:
// .collection("collection_name/doc_name/subcollection_name") in v8
// use getDocs() instead of getDoc() to fetch the collection
const qSnap = getDocs(subColRef)
console.log(qSnap.docs.map(d => ({id: d.id, ...d.data()})))

我在这里详细回答了doc()collection()(V8V9)的区别:

Firestore:在Web v9中添加新数据的模式是什么?

如果有人想在模块化Firebase V9中使用onSnapshot获得子集合内文档的实时更新,您可以这样实现:

import { db } from "./firebase";
import { onSnapshot, collection } from "@firebase/firestore";
let collectionRef = collection(db, "main_collection_id", "doc_id", "sub_collection_id");
onSnapshot(collectionRef, (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log("Id: ", doc.id, "Data: ", doc.data());
});
});

最新更新