Firebase and AngularFire - $add in a array - unexpected behaviour

272 views Asked by At
dayPath = ref.path.toString() + '/' + configId + '/screens/' + screenIndex + '/days/',
                                // the ref for the days object
                                daysRef = fbutil.ref(dayPath),
                                // the sync for the days object
                                daysSync = fbutil.syncObjectReference(daysRef);

                            // the collection as a $firebase array
                            var list = daysSync.$asArray(),
                                items = [],
                                number;
                            console.log(list);
                            list.$add({dummy: 'Test'});

According with the documentation, when I use $add with $asArray, the $add supposed to do a "push". But instead it's creating a hash key instead a numeric index.

So, the dummy: test has a parent containing a hash key. The expected is a numeric index, I mean : array item.

Can someone give me some help? I just have 1 week of experience in this database.

The result is this one...

 screens
 ...0
 .......days  
 ..........0
 ..........1
 ..........2
 .........-JrT5ZATDELIR3gXAvah
 ................dummy: test
2

There are 2 answers

1
Frank van Puffelen On

AngulareFire is built on the Firebase JavaScript SDK. So when AngularFire's documentation says it uses push internally, it is not referring to JavaScript's Array.push, but to Firebase's push operation. And Firebase's push generates its own keys, it does not generate regular array indexes.

The reason for that is best explained in Firebase's documentation on arrays, but essentially boils down to: arrays don't work well in distributed environments, because all clients have to agree on the array.length in order to be able to add a new item.

So $firebaseArray.$add will generated a so-called push ID. They are ordered, like array indexes, but can be generated across clients without risk of conflicts.

I noticed that you're on a somewhat older version of AngularFire. I highly recommend that you follow the "official" quickstart and guide for AngularFire.

2
André Kool On

I would like to comment but i don't have enough reputation yet so i'm doing it here.

The solution in my eyes is very simple:

Instead of:

list.$add({dummy: 'Test'});

Do:

list[index] = {dummy: 'Test'};