Reputation:
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.
Upvotes: 1
Views: 742
Reputation: 317352
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 => { ... })
Upvotes: 2
Reputation: 598668
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');
Upvotes: 0