steff feyens steff feyens - 5 months ago 47
iOS Question

Multiple Groups

I'm trying to create a chat app with groups. Players can join multiple groups. The problem that I'm facing is that I don't know how to add multiple groups to a player. If the player is joined in 1 group I could use 'Group' as key and the group name as value but with multiple groups this isn't possible. I can't create multiple 'Group' keys because then they aren't unique. Maybe an array as value for 'Group'? But I don't think this is possible. I hope someone can help me. Thanks!


You can use an array, but it's better to use an object with firebase-generated keys. See the proposed database structure below:

"root": {
    "users": {
        "$userId": {
            "groups": {
                "$groupId": true
    "groups": {
        "$groupId": {

I haven't coded for iOS, so the following example is in JavaScript. With the database structure above, you can add user to groups and read which groups the user is in like this:

var currentUserId = ?; // The userId of the logged in user
var currentUserGroupsRef = rootRef.child('user').child(currentUserId).child('groups');

// Join group
var groupId = ?; // The id of a group that the user joins
currentUserGroupsRef.child(groupId).set(true); // Add the groupId to the users groups, letting firebase generate an Id

// Read groups
currentUserGroupsRef.on('value', (snap) => {
    if (!snap.val()) {
        var userGroupIds = []; // user is not in any groups, empty array of groupIds
    var userGroupIds = Object.keys(snap.val()); // Array of groupIds