yooouuri
yooouuri

Reputation: 2658

Append to Firebase array without key

I have an array without keys. How can I append an element to the keyless array?

favorites:
- 0
  |
   -- name: "bs41"
- 1
  |
   -- name: "uie"

So my result would be:

favorites:
- 0
  |
   -- name: "bs41"
- 1
  |
   -- name: "uie"
- 2
  |
   -- name: "pts4"

Upvotes: 0

Views: 620

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599836

Your best approach here would be a transaction.

But as usual: there are a lot of reasons why Firebase recommends against using arrays.

For example: can the same value be specified twice in favorites? Chances are that each user can only specify each favorite only once. So one of your next questions in that case is going to be: how can I prevent duplicate values in this Firebase array? And the answer to that one is again going to be: with a transaction.

Transactions hurt the performance and scalability of your application; and it also means that your app won't work when the user of offline. Whenever you need a transaction, it pays off to wonder if there is a data model that accomplishes the same use-case that doesn't require a transaction.

For storing favorites that could be as simple as putting the values into the keys of the collection:

favorites:
    "bs41": true
    "uie": true
    "pts4": true

Now you have an automatic guarantee that each favorite value can be present only once. Adding a new item is also incredibly simple: ref.child("favorites").child("newfav").setValue(true).

The data model I just shared is how you model a set in Firebase. In my experience when you have an array/list and are checking if it contains a specific value before adding a new item, you often should be using a set instead.

Upvotes: 2

Related Questions