Let's assume that we want to create a unique identification number for a user (uid) in Firebase.
Like in Stack Overflow, the straightforward way is to create a counter in the database and assign the last value plus one to a new user.
Example:
javascriptconst getUid = async () => { let newUid; await admin.database().ref('/users/counter').transaction(value => { newUid = value + 1; return (value + 1); }); return newUid; }
Alternatively, we could create a unique identification number by concatenating 4 random strings of 4 characters.
Example:
javascriptconst getUid = () => { let wwww = Math.random().toString(32).slice(-4); let xxxx = Math.random().toString(32).slice(-4); let yyyy = Math.random().toString(32).slice(-4); let zzzz = Math.random().toString(32).slice(-4); return wwww + xxxx + yyyy + zzzz; }
If we try to launch this function 1000000 times, let's see how many duplicates we get:
javascriptlet random = {}; let duplicates = 0; for(let i = 0; i < 1000000; i ++){ let result = getUid(); if(!random[result]) random[result] = true; else duplicates ++; } console.log(duplicates); // 0
There are no duplicates for 1000000 users. Feel free to try the function with more iterations to check if there are collisions. If you encounter collisions, you could add more random chars to the getUid()
function.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.