While loop to check database

Hi,

I am trying to create unique usernames by doing the following,

  1. assigning a username

  2. checking that this username does not already exist
    if already exist, create a new 1 and then check this
    else, assign original username

 function createUsername(USER) {
 var check = false;
 while (check === false) {
            wixData.query("Teachers")
                .eq("username", USER)
                .eq("school", session.getItem('schoolID'))
                .find()
                .then((result) => {
 if (result.items.length === 0) { //username does not alredy exist
                        check = true;
 return USER;
                    } else {
 //create new username
 if (USER.length === 6) {
                            USER = USER + 1;
                        } else {
 let userStart = USER.substring(0, 5);
 let userEnd = +(USER.substring(5));
                            USER = userStart + (userEnd + 1).toString();
                        }
                    }
                })
                .catch((err) => {
 let errorMsg = err;
                });
        }
    }

The original assigned username (USER) is fed into the function.

The function is then called (not sure if that is the correct terminology).

However, this is not working. Can someone help please?
Thanks

I don’t like your idea with the loop.

But if you want to solve it in this way you have to wait for when the DB query will be done and then you can do another query

For example with async/await

async function createUsername(USER) {
 var check = false;
 while (check === false) {
            await wixData.query("Teachers")

Thanks @alexanderz61239 I will try this way.
If possible, can you explain why you do not like this idea, or of an alternative way to do such a thing?

I still cannot get this to work with the same error message…
Type ‘Promise’ is not assignable to type ‘string’

I am going to try to find an alternative way.
Thanks again for your help

Using the beforeInsert() data hook, you can check if the value to be inserted already exists in the database collection. If the value exists, the insert is rejected.

See the Example: No Database Duplicates .

thanks @yisrael-wix , will this stop two users at almost the same time being able to create the same username (because when they both check one doesn’t exist)

Hope this makes sense