1

When pushing a new record into a Firebase collection, I want to get the chronological id, a-la MySQL: 0, 1, 2, n - 1.

Is that possible with Firebase?

Here's the code snippet where I'm inserting a new record:

myCollection.set({
  id: id,
  foo: "bar"
});

The id variable should be the number of records - 1. Is there a built-in solution for that?

What's the best way to do it?

I tried to do:

id = myCollection.numChildren()

But since I don't want to fetch the entire collection in memory (using the once("value", ...) thingy), myCollection.numChildren is undefined.

Also, how can we ensure the id is unique?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • 1
    https://www.firebase.com/docs/web/guide/saving-data.html#section-push says you should use `push()` with an auto-generated unique id. – Simon Hänisch Sep 28 '16 at 12:05
  • @SimonHänisch `push().set({...})` creates the new record, but the id is a long one (e.g. `-Kno123asdasd...`). – Ionică Bizău Sep 28 '16 at 12:46
  • 2
    @IonicăBizău Perhaps you could consider using a `createdAt` timestamp on the object being pushed, then upon queries, you could simply retrieve as per which timestamp came first, because you say you want the data chronological manner, and timestamps are never the same, are they? – KhoPhi Sep 28 '16 at 12:48
  • @Rexford Another reason is to have *beautiful* ids—because they will be visible in the url: `/foo/edit/:id` (e.g. `/foo/edit/42`). – Ionică Bizău Sep 28 '16 at 13:05
  • 2
    Having a number in a URL is not objectively more beautiful than having another ID format. But the reasons why Firebase uses these so-called push IDs are quite well documented: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html, https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html and https://firebase.google.com/docs/database/web/save-data#append_to_a_list_of_data – Frank van Puffelen Sep 28 '16 at 14:22
  • @FrankvanPuffelen Thanks––makes sense, but still, what would be the solution in case we want to have a number as unique id and map it to the object? Answer is welcome (you can mention there the "good practice" and also a workaround/solution if any). :) – Ionică Bizău Sep 30 '16 at 15:33
  • A [quick search leads](https://www.google.com/search?q=firebase%20unique%20counter&rct=j) to some relevant results: http://stackoverflow.com/questions/28915706/auto-increment-a-value-in-firebase, https://jsfiddle.net/katowulf/5ESSp/, https://recalll.co/app/?q=%20%20Incremental%20ID%20example%20with%20Firebase%20%5BJavaScript%5D – Frank van Puffelen Sep 30 '16 at 18:15

0 Answers0