简体   繁体   中英

How can I get documents inside a subcollection in every document in Firebase Firestore?

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"

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 => { ... })

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM