0

I wonder how can I accomplish structure for my database. I am creating simply matchmaking app, I want to create relation one-to-many.

matches
   8aWcF6GQmpezfJkVnW5uYoJ2wtI3 //id for user
      8oqmrMVZ57XXlunIAUEeBgKFZ0h2 //id of matched users
      NzDaJNamKNVsWuP0FVaJI7b6Cuk1
      XzGWMuXrFYQ6m0MMVSwvpjSV4JF2

users
   8aWcF6GQmpezfJkVnW5uYoJ2wtI3
      email: "test@mail.com"
      uid: "8aWcF6GQmpezfJkVnW5uYoJ2wtI3"
      username: "john"
   NzDaJNamKNVsWuP0FVaJI7b6Cuk1
      email: "test2@mail.com"
      uid: "NzDaJNamKNVsWuP0FVaJI7b6Cuk1"
      username: "john2"
   XzGWMuXrFYQ6m0MMVSwvpjSV4JF2
     email: "aaaaa@mail.ru"
     uid: "8oqmrMVZ57XXlunIAUEeBgKFZ0h2"
     username: "aaaaa"

However, I cannot implement child to node, without value. So structure like above is not possible in Firebase Console to create.

Can you give me any suggestions?

KENdi
  • 7,576
  • 2
  • 16
  • 31
K.Os
  • 5,123
  • 8
  • 40
  • 95

1 Answers1

1

Firebase indeed cannot store a key without a value. So you have two options:

  1. Make up a key
  2. Make up a value

Let's cover the wrong solution first: making up a key.

Many developers choose for option 1: making up their own key. This typically then leads to them using an array:

matches
   8aWcF6GQmpezfJkVnW5uYoJ2wtI3 //id for user
      [ "8oqmrMVZ57XXlunIAUEeBgKFZ0h2", "NzDaJNamKNVsWuP0FVaJI7b6Cuk1", "XzGWMuXrFYQ6m0MMVSwvpjSV4JF2" ]

This seems very terse, but is the wrong solution. An array is an ordered collection that can contain the same value multiple times. In your data each user can be present only once. That means that we'd have to do an array.contains() each time we want to add a user.

A better solution is to make up a value. It doesn't really matter what value we use here, so the idiomatic value is true:

matches
   8aWcF6GQmpezfJkVnW5uYoJ2wtI3 //id for user
      8oqmrMVZ57XXlunIAUEeBgKFZ0h2: true
      NzDaJNamKNVsWuP0FVaJI7b6Cuk1: true
      XzGWMuXrFYQ6m0MMVSwvpjSV4JF2: true

Now the data structure still have the User IDs in the key, which also means that each user ID can only be in the collection once. This is essentially a Firebase Database implementation of a Set data structure.

Note that the true is no magic value here. So if you find you have the need for keeping some data for each user, you can easily store that instead of true.

For example, if you want to show the names of all friends, you can consider storing their names instead of true. It will save you having to look it up for each user. Of course this means that you have to figure out what you want to do if the user changes their name. See this answer for more on that: How to write denormalized data in Firebase

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807