Home > Net >  How to check if name already exists in Firebase Realtime Database (Firebase & JS)
How to check if name already exists in Firebase Realtime Database (Firebase & JS)

Time:10-02

I am trying to check if a name already exists on a Firebase Realtime Database that is structured as follows:

enter image description here

Here is my code:

const players = Firebase.database().ref("players");

function nameCheck() {
        console.log(name);

        players
        .orderByChild('settlement_name')
        .equalTo(name)
        .once('value')
        .then(snapshot => {
            if(snapshot.exists()){
                let playerData = snapshot.val();
                console.log(playerData)
                setError('Settlement name already exists')
                return playerData
            } else {
                console.log('Settlement name not found');
            }
        })
    }

Why this function is not correctly identifying when a name exists? I am logging the name at the start of the function and it matches those on the database, yet it will only return that the name is not found.

CodePudding user response:

You need to use the nested child path, as explained in the doc.

    players
      .orderByChild('settlement/settlement_name')
      ...

PS: In case you check if a name exists in order to use this name to create a new database node (if it does not exist), you should use a Transaction.

  • Related