0

I am new to firebase and trying to add a user to a chat group on login. My function currently appends the user to 'members' by using childbyautoid but this adds a firebase generated ID key and key titled uid.

What I want to do is generate the next number in the sequence as the key, and the user id as the value.

My function in Swift:

let key = self.databaseRef.child("groups").child("-LEf3_zagKHB6qQEbTL7").child("members").childByAutoId().key
let newuser = ["uid": uid]
let childUpdates = ["/members/\(key)": newuser]
self.databaseRef.child("groups").child("-LEf3_zagKHB6qQEbTL7").updateChildValues(childUpdates)

When I try to add a fourth member to the group, this is what I get in Firebase for the group "LEf3_zagKHB6qQEbTL7"...

{
  "description" : "The Tribe",
  "members" : {
    "0" : "5pw4MkVxKob8nXiHojTl61tQQ822",
    "1" : "FeP6H8H0PyVjMDcqwH3zbY0xAxg2",
    "2" : "ZtcfskmMydQmGIarYyKiuO6cKbh1",
    "-BdfJitm1T_fu1ssXcUY" : {
      "uid" : "dSiUpZfdRpXxE7WQL01T5lOUkfF2"
    }
  },
  "title" : "popupzendo"
}

What I am expecting to see is this...

{
  "description" : "The Tribe",
  "members" : {
    "0" : "5pw4MkVxKob8nXiHojTl61tQQ822",
    "1" : "FeP6H8H0PyVjMDcqwH3zbY0xAxg2",
    "2" : "ZtcfskmMydQmGIarYyKiuO6cKbh1",
    "3" : "dSiUpZfdRpXxE7WQL01T5lOUkfF2"
    }
  },
  "title" : "popupzendo"
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
JW Hall
  • 17
  • 1
  • 4

1 Answers1

1

If you want to sequently increment the index, you'll first have to read the entire array, determine the next index, set the new child at that index, and then write it back. The entire thing will have to happen in a transaction to remove the chance of somebody else also adding a child around the same time and them both getting the same index. This immediately also means that the operation won't work when the user is intermittently disconnected from the server.

If all of this sounds like it's trickier than expected, you might realize why Firebase's push() operation generates a different type of key. While it's much more complex than a sequential index, it bypasses all the problems mentioned before: it requires no transaction, it has no chance of collisions, and it doesn't even require the user to be connected to the server.

For more on why array indices are tricky to combine with massively multi-user scenarios, read the classic blog post Best Practices: Arrays in Firebase.

If you insist on using array indices, I recommend checking out these posts:

For more on handling lists in Firebase in Swift, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks Frank. I did some reading and I am glad to catch this now. I have solved the immediate problem and now will do some study and develop a new strategy for distributed data. Really appreciate your help and time and now I know why it was so hard to find an answer. – JW Hall Jun 10 '18 at 22:22