Home  >  Q&A  >  body text

Check if value exists in firebase database

<p>Is there a way in firebase to check if a value exists in the database? Firebase has method .exists() but according to the documentation it only checks the key. </p> <p>I have the following structure:</p> <pre class="brush:php;toolbar:false;">{ "users": { "-KKUmYgLYREWCnWeHCvO": { "fName": "Peter", "ID": "U1EL9SSUQ", "username": "peter01" }, "-KKUmYgLYREWCnWeHCvO": { "fName": "John", "ID": "U1EL5623", "username": "john.doe" } } }</pre> <p>I want to check if the ID with value <code>U1EL5623</code> exists. </p>
P粉354602955P粉354602955440 days ago419

reply all(2)I'll reply

  • P粉364642019

    P粉3646420192023-08-28 16:24:26

    If you want to check if an email exists in Firebase, here is a similar solution

    firebase.app().database().ref("shops").orderByChild("email")
       .equalTo(user.email).once("value", snapshot => {
    
                const userData = snapshot.val();
    
                // Check if it is a SHOP.
                if (userData) {
                  console.log("Shop logged in!");
                  this.setState({
                    isAdminLoggedIn: false,
                    isUserLoggedIn: false,
                    isShopLoggedIn: true,
                    isNoneLoggedIn: false
                  });
    
                // Check if it is a USER.
                } else {
                  console.log("User logged in");
                  this.setState({
                    isAdminLoggedIn: false,
                    isUserLoggedIn: true,
                    isShopLoggedIn: false,
                    isNoneLoggedIn: false
                  });
                }
            });

    reply
    0
  • P粉125450549

    P粉1254505492023-08-28 13:53:22

    The

    exists() method is part of the snapshot object returned by the Firebase query. So keep in mind that you won't be able to avoid retrieving the data to verify that it exists .

    // Firebase Namespaced SDK (v8 & older)
    // import firebase as appropriate
    
    const userQueryByID = firebase.database()
      .ref("users")
      .orderByChild("ID")
      .equalTo("U1EL5623");
    
    // using a snapshot listener
    userQueryByID
      .once(
        "value",
        snapshot => {
          if (snapshot.exists()){
            const userData = snapshot.val();
            console.log("exists!", userData);
          }
        }
      );
    
    // OR, using a promise
    userQueryByID.get()
      .then(snapshot => {
        if (snapshot.exists()){
          const userData = snapshot.val();
          console.log("exists!", userData);
        }
      });
    // Firebase Modular SDK (v9+)
    // import each function from "firebase/database"
    
    const rtdb = getDatabase();
    const userQueryByID = query(
      ref(rtdb, "users"),
      orderByChild("ID"),
      equalTo("U1EL5623")
    );
    
    // using a snapshot listener
    onValue(
      userQueryByID,
      snapshot => {
        if (snapshot.exists()){
          const userData = snapshot.val();
          console.log("exists!", userData);
        }
      },
      { onlyOnce: true }
    );
    
    // OR, using a promise
    get(userQueryByID)
      .then(snapshot => {
        if (snapshot.exists()){
          const userData = snapshot.val();
          console.log("exists!", userData);
        }
      });

    Observation results:

    If you are in a different scenario and you have the exact reference path where the object might be, there is no need to add orderByChild and equalTo. In this case you can get the path to the object directly, so no search processing is required from firebase. Also, if you know one of the properties that the object must have, you can follow the code snippet below and have it retrieve only that property instead of the entire object. The result will be faster inspections.

    For example, if each user had a username in their data, you could use these:

    // Firebase Namespaced SDK (v8 & older)
    // import firebase as appropriate
    
    const usernameRef = firebase.database()
      .ref(`users/${userId}/username`);
    
    // using a snapshot listener
    usernameRef
      .once(
        "value",
        snapshot => {
          if (snapshot.exists()){
            const username = snapshot.val();
            console.log("exists!", username);
          }
        }
      );
    
    // OR, use usernameRef.get() for a promise, as above
    // Firebase Modular SDK (v9+)
    // import each function from "firebase/database"
    
    const rtdb = getDatabase();
    const usernameRef = ref(rtdb, `users/${userId}/username`);
    
    // using a snapshot listener
    onValue(
      usernameRef,
      snapshot => {
        if (snapshot.exists()){
          const username = snapshot.val();
          console.log("exists!", username);
        }
      },
      { onlyOnce: true }
    );
    
    // OR, use get(usernameRef) for a promise, as above

    reply
    0
  • Cancelreply