Reputation: 69
example1) collection - doc - collection - doc - collection
example2) collection
example1 structure, I can import all the documents lists inside the last collection.
example2 structure, I can't get all the documents lists inside the collection.
how can i get top-level collection inside documents lists?
here is my code down here.
// this is example1. this is working!!
dbService
.collection("users")
.doc(uid)
.collection(uid)
.doc("video")
.collection(uid)
.onSnapshot((snapshot) => {
snapshot.docs.map((doc, index) => {
videoList.push(doc.data());
console.log(doc.data());
});
});
// this is example2. this is not working !!!!!
dbService
.collection("users")
.onSnapshot((snapshot) => {
snapshot.docs.map((doc, index) => {
videoList.push(doc.data());
console.log(doc.data());
});
});
example2 is return empty array. why is this?
Upvotes: -1
Views: 195
Reputation: 598847
Loading data from Firestore is shallow. This means that if you load documents from the users
collection, no data from subcollections is automatically included.
If you want to load data from a specific user's video
subcollection, you'll need to make an extra call:
dbService
.collection("users")
.onSnapshot((snapshot) => {
snapshot.docs.map((doc, index) => {
if (/* this is a user you are interested in */) {
snapshot.ref.collection(videos).get().then((videos) => {
videos.forEach((video) => {
videoList.push(video.data());
})
console.log(doc.data());
});
}
});
});
If you want to load all videos for all users you can use a so-called collection group query:
dbService
.collectionGroup("videos")
.onSnapshot((snapshot) => {
snapshot.docs.map((doc, index) => {
videoList.push(doc.data());
console.log(doc.data());
});
});
If you want to find the ID of the user for a specific video in here, you can find it with doc.ref.parent.parent.id
.
Upvotes: 1