1
votes

How can I get all the documents inside the subcollection "userPosts" in Firebase Firestore with JavaScript? You can see my database structure in the pictures below.

Here is what I have tried:

firebase.auth().onAuthStateChanged(function(user) {

    var postRef = database.collection('posts').doc().collection('userPosts');

    postRef.get().then(snapshot => {
        setupPosts(snapshot.docs)
    })

    const posts = document.querySelector('.posts');

    const setupPosts = (data) => {

        let html = '';
        data.forEach(doc => {
            const post = doc.data();

            console.log(post)

            const li = `
            <li>
                <div class="title">${post.title}</div>
                <div class="content">${post.content}</div>
            </li>
            `;
            html += li
        })

        posts.innerHTML = html;

    }
})

What this code should do is to get the documents in the subcollection "userPosts". And it should go into every document in the collection "posts" and then go into "userPosts" and get every document in that subcollection.

First collection "posts"

Subcollection "userPosts"

2
I'm not sure I understand. Can you show what you tried already, or why the code from this documentation doesn't work for you? firebase.google.com/docs/firestore/query-data/…Frank van Puffelen
I have now added the code I tried!user14362725

2 Answers

2
votes

It sounds like you want a collection group query. This will give you all the documents in all subcollections named "userPosts":

const query = database.collectionGroup("userPosts")
query.get().then(querySnapshot => { ... })
0
votes

This line makes no sense:

var postRef = database.collection('posts').doc().collection('userPosts');

The database.collection('posts').doc() creates a reference to a new, non-existing doc in the posts collection. Since you then its userPosts subcollection, this is of course going to not exist/be empty.


If you want to get the userPosts subcollection for your user argument, and you store the users based on their UID, then that'd be:

var postRef = database.collection('posts').doc(user.uid).collection('userPosts');