I'm trying to access the firebase firestore documents inside subcollection (messages):
user > user.uid > messages > docRef.id > date: Date.now()
text: userText
userEmail: user.email
userName: display.name
I used the following:
const snapRef2 = collection(db, "users/" user.uid "/messages")
onSnapshot(snapRef2, (snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.data());
})
})
But this method works only when user.uid is a string like: const snapRef2 = collection(db, "users/randomstring/messages")
How do I access the documents inside messages?
CodePudding user response:
The code in your answer works if you want to retrieve the messages for a specific user, identified by user.uid
.
If you want to get the messages for all users, you can use a collection group query. Such a query reads from all collections with a specific name, like messages
:
const snapRef2 = collectionGroup(db, "messages")
...
The rest of your code can stay the same.
CodePudding user response:
const snapRef2 = collection(db, `users/${user.uid}/messages`)
Make sure to use back ticks instead of quotation marks