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