How to get all the messages that the current user is sent

22 views Asked by At

I am trying to retrieve all the last messages that the current user sent to other users and display it in a listview. I cannot make the right query.Here is how my firestore database is structured. I will share it in two images.

This is my current query that does not work

String currentUser = FirebaseAuth.instance.currentUser!.uid;

// Get the messages where the current user is the sender
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('chat_rooms')
.where('senderId', isEqualTo: currentUser)
.orderBy('timestamp', descending: true)
.get();
print("the size of the snapshot is ${snapshot.size}");
1

There are 1 answers

1
Mäddin On

You are searching in the chat_rooms collection and not in the messages collection group.

QuerySnapshot snapshot = await FirebaseFirestore.instance
  .collectionGroup('messages')
  .where('senderId', isEqualTo: currentUser)
  .orderBy('timestamp', descending: true)
  .get();