Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
129
rated 0 times [  133] [ 4]  / answers: 1 / hits: 99413  / 8 Years ago, sun, june 19, 2016, 12:00:00

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.


More From » firebase

 Answers
28

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.


ref.child("users").orderByChild("ID").equalTo("U1EL5623").once("value",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.


//every user must have an email
firebase.database().ref(`users/${userId}/email`).once("value", snapshot => {
if (snapshot.exists()){
console.log("exists!");
const email = snapshot.val();
}
});

[#61713] Thursday, June 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
nolancampbellc questions
Thu, Sep 23, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
;