I am writing a function to generate a unique username for each new user. At first, assign a username matching with the full name of the user, then check that it exists in your database or not. If it exists then add some number to it and then check again until you come up with a new username that does not exist in the database.
Below is the code for the same
var generateUsername = function(name){
var username = name;
console.log(username);
var isUsername;
var number = 0;
db.collection("users").where("username", "==", username)
.get()
.then(function(querySnapshot) {
if(querySnapshot.empty){
isUsername = false;
}
else {
isUsername = true;
}
while(isUsername == true){
number++;
username = fullName + number;
console.log(username);
db.collection("users").where("username", "==", username)
.get()
.then(function(querySnapshot) {
if(querySnapshot.empty){
isUsername = false;
}
else {
isUsername = true;
}
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
}
This is not giving me desired output. The loop is running infinitely. Whhere I am doing wrong?