Firebase: how to generate a unique numeric ID for key?
Adding to the @htafoya answer. The code snippet will be
const getTimeEpoch = () => {
return new Date().getTime().toString();
}
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 callingset()
is so common that we let you combine them by just passing the data to be set directly topush()
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
As explained above, you can use the Firebase default push id.
If you want something numeric you can do something based on the timestamp to avoid collisions
f.e. something based on date,hour,second,ms, and some random int at the end
01612061353136799031
Which translates to:
016-12-06 13:53:13:679 9031
It all depends on the precision you need (social security numbers do the same with some random characters at the end of the date). Like how many transactions will be expected during the day, hour or second. You may want to lower precision to favor ease of typing.
You can also do a transaction that increments the number id, and on success you will have a unique consecutive number for that user. These can be done on the client or server side.
(https://firebase.google.com/docs/database/android/read-and-write)