I have a Firebase Realtime DB structured like this:
users
userid1
name: "name1"
email: "email1"
specialValue: "special"
userid2
name: "name2"
email: "email2"
I want to check if a user(I already have a userid) has the specialValue key. So this should return true for userid1, and false for userid2.
I have tried this:
var check = firebase.database().ref('users').orderByKey().equalTo(userid).once("value", function (snapshot) {
if (snapshot.exists()) {
console.log("key exists");
} else {
console.log("key doesn't exist");
}
});
You don't need a query for a node if you know the key, so this should work (and be a bit faster once you have a lot of nodes):
firebase.database().ref('users').child(userid).once("value").then((snapshot) => {
if (snapshot.exists()) {
console.log("exists");
} else {
console.log("doesn't exist");
}
});
In addition to being shorter and faster, this also is guaranteed to give just one snapshot as a result, where a query may have multiple results. Even though your query will only match one result, the API still returns the one result as a list and you'd have to loop over that with forEach.