Firebase: how to generate a unique numeric ID for key?

Ivan Wang picture Ivan Wang · Mar 3, 2015 · Viewed 124.1k times · Source

I need numeric IDs for human readability. How do I get it in Firebase?

I want numeric ID for keys, e.g. "000000001", "000000002","00000003","00000004".

The reason I need it is because these IDs will become the permanent object ID both online and offline. I want users to be able to browse that object page by just entering URL "/objects/00000001" without efforts.

I am asking here, because I want to know if this can be done without using .priority, sub-properties, etc. I guess set method can do it somehow. If it is not possible, just tell me no, I can accept that answer.

Answer

Sinan Bolel picture Sinan Bolel · Mar 3, 2015

I'd suggest reading through the Firebase documentation. Specifically, see the Saving Data portion of the Firebase JavaScript Web Guide.

From the guide:

Getting the Unique ID Generated by push()

Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});
// Get the unique ID generated by push() by accessing its key
var postID = newPostRef.key;

_Source: https://firebase.google.com/docs/database/admin/save-data#section-ways-to-save * A push generates a new data path, with a server timestamp as its key. These keys look like -JiGh_31GA20JabpZBfa, so not numeric. * If you wanted to make a numeric only ID, you would make that a parameter of the object to avoid overwriting the generated key. * The keys (the paths of the new data) are guaranteed to be unique, so there's no point in overwriting them with a numeric key. * You can instead set the numeric ID as a child of the object. * You can then query objects by that ID child using Firebase Queries.

From the guide:

In JavaScript, the pattern of calling push() and then immediately calling set() is so common that we let you combine them by just passing the data to be set directly to push() as follows. Both of the following write operations will result in the same data being saved to Firebase:

// These two methods are equivalent
postsRef.push().set({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});
postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

_Source: https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push