0
votes

I'm trying to add something to rooms/users using a data model that looks like this:

rooms: {
    name: roomname
    users: {
        0: [email protected]
    }
}

My question is if there is any way to append a new item to the users array. I would normally do this using update(), but update() requires a key for the data to be set to when I just want to set it to the next array index. I figure that I can do this by getting the current rooms/users array, appending to it locally, and using set() to overwrite it, but I was wondering if there was a better (built in) way to go about this.

1
Your previous question and this one are pretty well covered in Firebase's documentation. I recommend starting with the AngularFire docs (firebase.com/docs/web/libraries/angular) and then skimming through the regular web docs (firebase.com/docs/web/guide) for completeness. - Frank van Puffelen
@FrankvanPuffelen Thanks again. I never read the full documentation, just the 'quick start' guide and only checked the docs when I was looking for something. I'll definitely read over them now. - Lars Honeytoast

1 Answers

1
votes

Using arrays in a potentially massively distributed system such as Firebase are in general a bad idea. And from what you've described, your use-case falls under the "in general" category.

From the Firebase documentation on arrays:

Why not just provide full array support? Since array indices are not permanent, unique IDs, concurrent real-time editing will always be problematic.

Consider, for example, if three users simultaneously updated an array on a remote service. If user A attempts to change the value at key 2, user B attempts to move it, and user C attempts to change it, the results could be disastrous. For example, among many other ways this could fail, here's one:

// starting data
['a', 'b', 'c', 'd', 'e']

// record at key 2 moved to position 5 by user A
// record at key 2 is removed by user B
// record at key 2 is updated by user C to foo

// what ideally should have happened
['a', 'b', 'd', 'e']

// what actually happened
['a', 'c', 'foo', 'b']

Instead of using arrays, Firebase uses a concept called "push ids". These are consistently increasing (like array indices), but (unlike array indices) you don't have to know the current count to add a new push id.

With push ids, you can add a new user with:

var ref = new Firebase('https://yours.firebaseio.com/rooms/users');

ref.push('[email protected]');

Note that the Firebase documentation is in general considered to be pretty good. I highly recommend that you follow at least the programming guide for JavaScript, from which I copied the above.