63

Is there a method in firebase, which can check if value exist in DB? Firebase has method .exists(), but according to docs it checks only the keys.

I have the following structure:

{
  "users": {
    "-KKUmYgLYREWCnWeHCvO": {
      "fName": "Peter",
      "ID": "U1EL9SSUQ",
      "username": "peter01"
    },
    "-KKUmYgLYREWCnWeHCvO": {
      "fName": "John",
      "ID": "U1EL5623",
      "username": "john.doe"
    }
  }
}

I want to check if ID with value U1EL5623exists.

Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

4 Answers4

97

The exists() method is part of the snapshot object which is returned by firebase queries. So keep in mind that you won't be able to avoid retrieving the data to verify if it exists or not.

// 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);
    }
  });

Observations:

In case you are in a different scenario which you have the exact ref path where the object might be, you wont need to add orderByChild and equalTo. In this case, you can fetch the path to the object directly so it wont need any search processing from firebase. Also, if you know one of the properties the object must have you can do as the snippet below and make it retrieve just this property and not the entire object. The result will be a much faster check.

For example, if every user has a username in their data, you can 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
samthecodingman
  • 23,122
  • 4
  • 30
  • 54
adolfosrs
  • 9,286
  • 5
  • 39
  • 67
  • how you can do this with angularfire2 ?? – Cesar Vega May 26 '17 at 14:33
  • 1
    @Xvegas you can do it similarly like this: `const dbRef = this.db.database.ref(); dbRef.child(childName).orderByChild(objKey).equalTo(keyToCheck).once('value', snapshot => { // your code here });` The `orderByChild` part is very important. It didn't work for me without it. – Matheus CAS Aug 26 '17 at 18:49
  • how do I search if the key "ID" is not known? – Nikhil Jan 10 '19 at 03:51
  • @Nikhil Not known or dynamic? If you don't know which key you are looking for you won't be able to check if it exists or not. – adolfosrs Jan 10 '19 at 03:55
  • so what I mean is inside of the topic "KKUmYgLYREWCnWeHCvO", I want to search for any value say "Peter". I don't care which key matches – Nikhil Jan 10 '19 at 04:00
  • @adolfosrs Do you know if it's possible to limit the query to the documents that have a particular field? Say, only documents where document.completed exists? – Pim Dec 11 '19 at 21:01
  • @Pim Is `completed` a boolean property? If so you could just use `orderByChild('completed').equalTo(true)` – adolfosrs Dec 12 '19 at 02:00
  • @adolfosrs It's not a boolean unfortunately – Pim Dec 13 '19 at 23:19
  • How do you handle the event where the value does not exist? @adolfosrs? – EnigmaTech Dec 20 '19 at 14:12
  • @DerryckDX Would you please elaborate on that? In case the value does not exist the `exists()` would return `false`. You could open a new question here in SO with an example and more details to address that better :) – adolfosrs Dec 20 '19 at 14:22
  • @adolfosrs That's exactly what I was looking for. I needed to check if an email exists in the users collection. – Abrar Hossain Feb 29 '20 at 15:17
  • "So keep in mind that you won't be able to avoid retrieving the data to verify if it exists or not", isn't it the same as just doing a "find" in js on the front end if you pull the data anyways? @adolfosrs – FabricioG Mar 07 '20 at 06:58
  • I like this method of searching for the data faster than getting the whole object. nice answer – dave o grady Apr 03 '20 at 22:29
  • @FabricioG Sorry, not sure if I get what you meant. – adolfosrs Jul 07 '21 at 18:39
  • @adolfosrs As this is a good duplicate target, please consider appending the modern JavaScript SDK syntax to the answer. Alternatively, I can edit it into your answer with your go-ahead. – samthecodingman Aug 10 '23 at 09:44
  • @samthecodingman sure mate, that would be much appreciated. – adolfosrs Aug 15 '23 at 17:12
3

This is a similar solution if you want to check if an email exists in firebase

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
              });
            }
        });
Riccardo Persiani
  • 702
  • 1
  • 5
  • 25
1

I can't make comments yet, so I'm posting an answer:

To add to the suggested answer, if you wanted to query whether or not any users exist, you can try to improve performance by adding .limitToFirst(1) or .limitToLast(1). This way you can limit your retrieved data to the minimum:

//Check if any users exist
firebase.database().ref(`users`).limitToFirst(1).once("value", snapshot => {
   if (snapshot.exists()){
      console.log("exists!");
      // TODO: Handle that users do exist
      return true;
   }

   // TODO: Handle that users do not exist
});

sources: https://firebase.google.com/docs/reference/js/firebase.database.Query#limitToFirst

Mark Thompson
  • 448
  • 5
  • 7
1

This is how I searched for a url value in Firebasebase database on my project:


const searchFirebase = (url, idx) => 
{
     firebase
       .app()
       .database()
       .ref("recipes")
       .orderByChild("url")
       .equalTo(url)
       .once("value", (snapshot) => {
         if (snapshot.exists()) {
           const userData = snapshot.val();
           console.log("exists!", userData);
           document.querySelector(`[data-recipe-id="${idx}"]`)
           .classList.replace('fav-heart', 'unfav-heart'); 
         } else {
           return false; 
         }
       });
}

bqh5026
  • 21
  • 2