Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create auto incremented key in Firebase?

I was wondering if we could create auto increment ID's(Keys) in Firebase like we have in SQL!

I was wanting to create a structure like this

rules:
  Line1:
    1: Smith
    2: Alex
    3: Hello
  Line2:
    1: Brown
    2: Michael

So lets say if I want to add "Erik" to Line 1 it should do it like this

Line1:
    1: Smith
    2: Alex
    3: Hello
    4: Erik

Is it possible have structure like that?

I do know we have

push()

and

childByAutoId()

but this does not fit for my problem. I am working with Swift iOS just.

like image 928
Neel Patel Avatar asked Sep 15 '16 19:09

Neel Patel


People also ask

How do I increment a number in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.

What is getKey () in Firebase?

public String getKey () Returns. The key name for the source location of this snapshot or null if this snapshot points to the database root.

What is Firebaseio COM used for?

Firebase provides detailed documentation and cross-platform SDKs to help you build and ship apps on Android, iOS, the web, C++, and Unity.


1 Answers

Such sequential keys inherently limit the scalability of a multi-user distributed system that also needs to deal with a lack of connectivity. That's one of the reasons why Firebase doesn't support them.

Instead Firebase has its own key type, called push IDs. Like the sequence you're looking for these are monotonously increasing, and they are also guaranteed to be unique. But the big difference is that push IDs, unlike the sequence numbers of most SQL databases, can be determined client side.

For more information on arrays (which are similar to sequences) in Firebase, see this blog post: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html.

For more information on Firebase's push IDs, see this blog post: https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html

If you still decide that you must use sequential IDs, have a look at Kato's implementation of that here: http://jsfiddle.net/katowulf/5ESSp/. The core of this is keeping a counter property in the database with the current highest sequence number, and then using a transaction to update that.

like image 97
Frank van Puffelen Avatar answered Sep 22 '22 12:09

Frank van Puffelen