Test If a Data Exist in Firebase

Test if a data exist in Firebase

You can use DataSnapshot.hasChild to determine if a certain child exists.

usersRef.once('value', function(snapshot) {
if (snapshot.hasChild(theDataToAdd)) {
alert('exists');
}
});

Here's a quick jsfiddle showing how this works: http://jsfiddle.net/PZ567/

But this will download all data under usersRef and perform the check on the client. It's much more efficient to only download the data for the user you want to check, by loading a more targeted ref:

usersRef.child(theDataToAdd).once('value', function(snapshot) {
if (snapshot.exists()) {
alert('exists');
}
});

check if data exist in Firebase Database

Can you try adding

if (dataSnapshot.hasChild(dataToAdd)) {
// data exist
}

Doc: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot.html#haschild

Check if value exists in firebase DB

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

How to verify if data exist in Firebase

take a look to this code right here :

function go() {
var userId = prompt('Username?', 'Guest');
checkIfUserExists(userId);
}

var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';

function userExistsCallback(userId, exists) {
if (exists) {
alert('user ' + userId + ' exists!');
} else {
alert('user ' + userId + ' does not exist!');
}
}

// Tests to see if /users/<userId> has any data.
function checkIfUserExists(userId) {
var usersRef = new Firebase(USERS_LOCATION);
usersRef.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}

Check for existence of value in firebase realtime database?

The get(<query>) returns a DataSnapshot that still has exists() which returns true if this DataSnapshot contains any data.:

const q = query(dbRef, orderByValue(), equalTo(testURL));

const snapshot = await get(q);

if (snapshot.exists()) {
const results = snapshot.val();
console.log('Results', results)
} else {
console.log('Data does not exist')
}

From the documentation,

To filter data, you can combine any of the limit or range methods with an order-by method when constructing a query.

So adding orderByValue() in query should solve the issue.

How to check if a value exists in firebase

Try this:

boolean CheckExists =false;   //declare and assign default value in global scope

reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();

for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields

if(u.email.equalsIgnoreCase(Email.getText().toString())){
CheckExists =true;
}
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});

How to check if data exist in firebase. (KivyMD Python)

Did you try with firebase_admin?

I check my data with like this:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

cred = credentials.Certificate(
"firestore-cred.json"
)
firebase_admin.initialize_app(cred)
db = firestore.client()
data = {
"Email" : email
}

query_email = db.collection(u'Users') \
.where(u"Email",u"==",data["Email"]) \
.get()
if query_email:
# exists
...
else:
# does not exist
...

If user email does not exist, query_email is going to be empty list.
Do not forget that query_email is not json data. You can convert it json with to_dict():

email_query_result_as_json = query_email[0].to_dict()

Checking if Firebase data exists as a condition

I was able to solve the problem by using if (snapshot.exists) as a conditional statement as shown below:

function userLogin() {
traceFunction()
console.log('userLogin')
if (checkLogin()) {
console.log('userLogin checkLogin is true')
hideInputText()
left_button.style.visibility = 'hidden'
showLogoAnimation()
user_dict = getUserDict()
if (user_dict) {
console.log('userLogin user_dict is ', user_dict)
hideLogoAnimation()
handleWelcome(is_first_time = false)
} else {
console.log('userLogin unable to find user_dict, preparing needed data')
user_dict = getQuestions().then(user_dict => createProfile(user_dict)).then(function () {
console.log('userLogin user_dict is ', user_dict)
hideLogoAnimation()
handleWelcome(is_first_time = true)
})
}
}
}

function getUserDict() {
let current_user_id = firebase.auth().currentUser.uid
let snapshot = firebase.database().ref().child('profile').child(current_user_id).child('user_dict').once('value')
if (snapshot.exists) {
return snapshot.val()
} else {
return false
}
}

How to check if value exists in Firebase Realtime Database (Dart/Flutter)?

once() always yields a DataSnapshot object. You have to check if that snapshot contains any data by looking at its value property.

  if (snapshot.value == null) {
print("Item doesn't exist in the db");
} else {
print("Item exists in the db");
}


Related Topics



Leave a reply



Submit