0

I am saving some data to firebase, I am using golang admin sdk. My problem is when I push object to firebase it generates an ID which is good for some use cases, but I don't need that what need is a custom integer key like 1,3,4..... The object may look like this after pushing.

enter image description here

I know I can set it by fetching all data then count them and create next id and add my object under that ID but I don't want this. Is there any way to achieve this in firebase automatically.

Abdul Momen
  • 379
  • 2
  • 13
  • Does this answer your question? [Setting custom key when pushing new data to firebase database](https://stackoverflow.com/questions/37483406/setting-custom-key-when-pushing-new-data-to-firebase-database) – Kundan Apr 20 '21 at 05:26
  • Either you accept the random string that you get from a push, or you specify the key value yourself. There are no autoincrement IDs. – Doug Stevenson Apr 20 '21 at 05:41
  • Thanks @Stevenson I thought so. It would be awesome if firebase could provide a feature like this. – Abdul Momen Apr 20 '21 at 05:45
  • You can store the last integer in any other node in the database and fetch it while adding new data. After that just increment the value in the other node . – Dharmaraj Apr 20 '21 at 07:03
  • 1
    Auto-incrementing integer (or other) keys are generally not a good idea in NoSQL databases. For what purpose are your wanting to do that? – Jay Apr 20 '21 at 15:58
  • Hello @Jay, as i have some data previously added and i don't want to break mobile and client side code. – Abdul Momen Apr 21 '21 at 08:09

1 Answers1

2

You can technically do this but it requires some additional setup. You will have to maintain the current index in a 'global' position and increment it

there is a risk of write failure if there is a race condition between 2 or more users. to minimize this, you can look at using transactions and rules to control the flow of data.

Additionally, you can use cloud functions to process this if you don't want the client to handle the transaction and updating of the global counter.

Sources:

Cloud Functions

Server side increment

Rules for existing vs new data

DIGI Byte
  • 4,225
  • 1
  • 12
  • 20