Vito Medlej
Vito Medlej

Reputation: 171

Firebase v9 ,Cannot get document from a nested collection

I feel like it was easier to get subcollection in v8 ,It's been like 2 days trying to do it the new way but I gave up.

Im building a simple react social media app for learning purposes. where each user logs in and be able to post some text (and images but not atm), I have a main collection for Users and it has the users ID .each of these users have a collection called Posts and it contains all the user posts.

here i want to access the Post collection for each user and then access the posts

I can do so by entering the UID of each user like so

but I can only access the current user id

so what can i do to access the Users collection then get ALL the users and be able to access the Posts subcollection?

ps : sorry if any part of this question is unclear ,english isn't my first language and it's my first time posting here. appreciate any help!.

Upvotes: 3

Views: 3125

Answers (3)

Amar Krishna
Amar Krishna

Reputation: 1

I have a structure like this

"posts" is a collection and it contains different "user IDs" documents and the "user IDs" contain a collection called "photos" which contain different documents which contain information about a post a user has created

To access all the posts of a user, I made use of

 const docRef = doc(db, 'posts', auth.currentUser.uid)
 const docSnap = await getDocs(collection(docRef, "photos"))
 docSnap.forEach((doc) => {
    // doc.data() is never undefined for query doc snapshots
    console.log(doc.id, ' => ', doc.data())
 })

Upvotes: 0

Muhammad Huzaifa
Muhammad Huzaifa

Reputation: 21

const docRef = doc(db, "Users", currentUser.uid);
const docSnap = await getDocs(collection(docRef, "Posts");)

Upvotes: -1

Dharmaraj
Dharmaraj

Reputation: 50850

If you want to fetch posts from all the users, you are looking for collectionGroup queries using which you can fetch documents in all the sub-collections named as 'posts'. You can run a collectionGroup query using Modular SDK (V9) as shown below:

import { getFirestore, getDocs, collectionGroup } from "firebase/firestore"
const db = getFirestore()

const allPosts = await getDocs(collectionGroup(db, "posts"))

Upvotes: 3

Related Questions