I'm working on a practice chat app here. Been a couple years since using Firestore the last time.
I'm using v9 and having trouble getting this nested "messages" collection if the "users" array in the document contains a specific ID. I am easily able to return the users array itself just fine or the doc ID, just can't seem to find something in the official docs or elsewhere that will also return the collection.
Here is an image of my Firestore setup below:
export const getConversations = async (userID) => {
const messagesQ = query(collectionGroup(db, 'conversations'), where('users', 'array-contains', userID))
const querySnapshot = await getDocs(messagesQ)
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data())
})
}
The code snippet above is the best I can seem to come up with, but like I said, it obviously only returns the users array itself. Not the messages collection.
CodePudding user response:
With your current structure, the best you can do is loop over the results you currently get, and access the messages
subcollection for each of them.
If you want to retrieve documents from the messages
collection you'll have to ensure those documents contain the same users
information that you have in the conversations
document now. With that you can then do a collection group query on messages
instead of conversations
.
To get a reference to the subcollection of the conversations
results:
querySnapshot.forEach((doc) => {
const messagesRef = collection(doc.ref, "messages");
})