[英]How to get a Subcollection inside a Collection in Firestore Web Version 9 (Modular)?
我正在使用 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");
但它對我不起作用,因為我在子集合中有一個列表 os docs,我想檢索它。 那么我怎樣才能在我的子集合中獲取我的所有文檔呢?
感謝任何花時間的人。
您需要使用collection()
來獲取CollectionReference
而不是返回DocumentReference
的doc()
:
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()
(在V8
和V9
)之間區別的詳細答案:
如果有人想在 Modular 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());
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.