0

I am developing a Chat application with Flutter and Firebase Realtime Database. Below is my JSON Stucture.

{
  "chat_room" : {
    "-MMR-dPo0A0nG4hcVW2j" : {
      "chat_mode" : "Supplier",
      "last_message" : "Test",
      "timestamp" : 1605713958580
    },
    "-MMRMbKC-818t2rg9UU5" : {
      "chat_mode" : "Supplier",
      "last_message" : "Test",
      "timestamp" : 1605719979342
    }
  },
  "members" : {
    "-MMR-dPo0A0nG4hcVW2j" : {
      "-MMR-dUUrMP1pDUZDMU3" : {
        "email" : "someone@test.com",
        "profile_pic" : "",
        "userID" : 30,
        "user_role" : "customer"
      },
      "-MMR-dYyDNdZfyLdCHD1" : {
        "email" : "anotherone@test.com",
        "userID" : 50,
        "user_role" : "supplier"
      }
    },
    "-MMRMbKC-818t2rg9UU5" : {
      "-MMRMbP_ucK89HU-yKaW" : {
        "email" : "someone@test.com",
        "profile_pic" : "",
        "userID" : 30,
        "user_role" : "customer"
      },
      "-MMRMbTzL3x3I9BqLxOD" : {
        "email" : "anotherone@test.com",
        "userID" : 50,
        "user_role" : "supplier"
      }
    }
  }
}
  1. I am first creating a chat_room
  2. Then I am adding the chat room users into the members
  3. To identify which member belong to which chat_room, I am adding the chat_room unique key as the foreign key in members and adding all the related members under that.

Now my question is, I am in need of searching the members by the email attribute and get all member records associated with. For an example, I need to search members for the records where the email is someone@test.com.

This is my current code, but its not giving what I need. I also know it is incorrect.

final DatabaseReference reference = FirebaseDatabase.instance.reference().child('members');
reference.orderByChild("email").equalTo("someone@test.com").once()

How can I perform this data retrieve in Flutter? If my chat app data structure is invalid, I am open for suggestions for a better structure.

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • Your data structure has two levels of nesting under the node you query. Firebase Realtime Database queries can only have one dynamic level, so the value you order/filter on must be at a fixed path under each direct child node. See https://stackoverflow.com/questions/27207059/firebase-query-double-nested and https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value. – Frank van Puffelen Nov 18 '20 at 18:29
  • @FrankvanPuffelen Thank you. I think I will require to change the database structure. I read your answers in the given links. Then, maybe best to shift into a data se structure like this? https://stackoverflow.com/a/58407016/1379286 – PeakGen Nov 18 '20 at 21:25
  • @FrankvanPuffelen Also in th link I shared and In the links you provided, settings 'Set' data type has been discussed. Please advise how we can set that data type in JSON when we are using `push.set()` – PeakGen Nov 18 '20 at 21:27

0 Answers0