Check if value exists in firebase database
P粉354602955
2023-08-27 19:51:39
<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>
If you want to check if an email exists in Firebase, here is a similar solution
The
exists()
method is part of thesnapshot
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 .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
andequalTo
. 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: