Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase/firestore get nested collection

I have a document that has a nested collection. I've been trying to get that nested collection using the firebase/firestore library as documented here: https://firebase.google.com/docs/reference/js/firebase.firestore

let route = await firebase.firestore()
.collection('route')
.doc('0bayKbCiAchc0Vy9XuxT')
.collection('qa')
.get()

I just get back PayloadTooLargeError: request entity too large

Any ideas? Is this not supported with this library?

like image 594
Senica Gonzalez Avatar asked Aug 25 '26 11:08

Senica Gonzalez


2 Answers

It has to do with how I was accessing route afterwards.

Just changed up a bit:

let snapshot = await firebase.firestore()
.collection('route')
.doc('0bayKbCiAchc0Vy9XuxT')
.collection('qa')
.get()

snapshot.forEach(doc =>{
  console.log('hello', doc.data())
})
like image 160
Senica Gonzalez Avatar answered Aug 28 '26 02:08

Senica Gonzalez


Answer for firebase version 9 (firebase 9.9.2) in 2022

assume you have firestore instance running:

const firebaseConfig = {
    your keys ...
};

let firebaseAppInstance;
if (getApps().length) {
  firebaseAppInstance = getApp();
} else {
  firebaseAppInstance = initializeApp(firebaseConfig);
}

export const firestore = getFirestore(firebaseAppInstance);

then assume you wanna acces nested collection with path as:

users (collection) / aXwAZdBRYHWrS36i.. (document uid <-- this is important, as it will be the only arg in the final function) / posts (desired nested collection)

do following:

export async function getPostsCollectionNestedInUserByUid(uid) {
  // ref to nested collection in the user:
  const postsInUserRef = collection(firestore, `users/${uid}/posts`);

  // order / limit etc them:
  const q = query(postsInUserRef, orderBy("createdAt"));

  // async get data:
  const postsInUserSnapshot = await getDocs(q);
  const arr = [];
  postsInUserSnapshot.docs.map((d) => {
    arr.push(d.data());
  });

  return arr;
}
like image 28
biscarrosse Avatar answered Aug 28 '26 00:08

biscarrosse