Ana
Ana

Reputation: 25

How to query from other collection in firebase?

Im new to firebase, and im implementing a comment feature and i have this structure on the firestore:

 - User

     - UserID
     - Name
     - Picture


----------

 - Post
    - PostID
    - Comments
       - CommentID
       - PostID
       - UserID

I want to display the comments in each posts with the name and the picture of a user who commented. How can I do that? I have the userID of the commentor, is it possible to access the user User collection using that? Or is there something wrong with my database structure?

Im planning to include the name and the picture of the user inside the Comment collection but when the user updates their name and picture, how can i update the one on the Comment collection?

Upvotes: 1

Views: 416

Answers (2)

crispengari
crispengari

Reputation: 9321

i don't know if i get what you've asked well, but you can try this.

FirebaseFirestore.instance
    .collection("Post").doc(PostID).collection("Comments")
    .where("userID", "==", userID)
    .get().then(snapshot =>{
           console.log(snapshot.docs.map(doc=>({id: doc.id, 
               data: doc.data()})))
      } )

The best way of dealing with this, is whenever the user posts a comment grab their data and post it in the comments collection, so that next time when you query you just get the comment and the person who commented.

Good Luck

Upvotes: 0

lenz
lenz

Reputation: 2425

This will get you the user with userID from the other collection.

FirebaseFirestore.instance
    .collection("User")
    .where("userID", isEqualTo: userID)
    .get();

Upvotes: 1

Related Questions