Home > OS >  How to get all documents on a nested firebase collection
How to get all documents on a nested firebase collection

Time:12-07

I have a nested subcollection that looks like:

users > user.id > cart > doc.id

And I am trying to get ALL documents on that collection. Here's how I get a single one:

useEffect(() => {
  const getStyleProfile = async (user: any) => {
  if (user) {
    const docRef = doc(db, "users", `${user.uid}`, 'cart', `${1}`);
    onSnapshot(docRef, (doc) => {
      setStyleProfile(doc.data())
    });
  }
  }
  getStyleProfile(user)

}, [user?.uid])

Which returns the first document:

{price: 400, property_id: 1} 'style values'

My question is: how can I return all the documents, no matter the ID?

Any question I've seen doesn't relate to subcollections, so not sure how to get it working, e.g this one

CodePudding user response:

As shown in the documentation, you build a reference to a collection like this:

const usersCollectionRef = collection(db, 'users');

You build a reference to a subcollection in much the same way:

const userCartsCollectionRef = collection(db, 'users', uid, 'carts);

The collection reference is queried exactly the same way no matter how deeply nested it is, as illustrated in the documentation.

const querySnapshot = await getDocs(userCartsCollectionRef);
  • Related