Demir
Demir

Reputation: 859

how to get nested collections data from firestore

I have a firestore collection like the following. I need to get the last stored message.

Firestore-root
  |
  --- chat_rooms(collection)
        |
        --- chats(collection, the id for that collection is sender_reciever)
             |
             --- time_send: (millisecondsSinceEpoch)
             |
             --- sender:(string)
             |
             --- message:(string)



This is my db method to get the last messaeg

  getLastMessage(String chatRoomId) {
    return  Firestore.instance.
    collection('chat_rooms').document(chatRoomId)
        .collection('chat').orderBy('time_send',descending: false)
        .limit(1).get();
  }

Here I am calling it. Chats is a widget that returns the sender and last_message. Basically what I am trying to do is, for instance, while using whatsapp the last message pops on home page.I am trying to do exact same thing.In that way, I could get the username too. The method below does not return actual user data. Since the collection chat_rooms_id has an id that is combination of username_sender and username_reciever. I am just removing the reciever which is the current user.And, the sender remains.

   return Chats(
                      username: snapshot.data.documents[index]
                          .data["chat_room_id"] // return chat_room id
                          .toString()
                          .replaceAll("_", "")
                          .replaceAll(Constants.signedUserName, ""),
                      chatRoomId:
                          snapshot.data.documents[index].data["chat_room_id"],
                      last_message: __db
                          .getLastMessage(snapshot
                              .data.documents[index].data[snapshot.data.documents[index]
                                  .data['chat_room_id'].toString()]
                              .toString()).toString()
                    );

The result is Result

Upvotes: 0

Views: 169

Answers (1)

Aakash kondhalkar
Aakash kondhalkar

Reputation: 680

First, create a class to store Chat info

class Chat {
  final String id;
  final time_send;
  final String sender;
  final String message;
  
  Chat({this.id, this.time_send, this.sender, this.message});
  
  
  static Chat fromSnapshot(QuerySnapshot snap) {
    return Chat(
      id: snap.id,
      time_send: snap.get('time_send'),
      sender: snap.get('sender'),
      message: snap.get('message'),
    );
  }
}

Then, modify your Firestore query as below, use snapshots() instead of get() method

Stream<Chat> chat(String chatRoomId) {
  return  Firestore.instance.
    collection('chat_rooms').document(chatRoomId)
    .collection('chat').orderBy('time_send',descending: false)
    .limit(1)
    .snapshots()
    .map<Chat>((snapshot) {
       if (snapshot.size > 0) {
          return snapshot.docs.map((e) => Chat.fromSnapshot(e)).single;
       } 
 });

Upvotes: 1

Related Questions