Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a data exist in Firebase

I would like test if a data exist in Firebase before to add it. But I have a problem with my method: I try to list all data with this Javascript code:

var theDataToAdd = userName; var usersRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/'); usersRef.on('child_added', function(snapshot) {    var message = snapshot.val();    if (message.name == theDataToAdd)       alert ("exist"); }); 

But if the user doesn't exist, it will be added before, then my code says that he exists. You will say that is normal because my alert is called only when "child_added", but I don't see how do.

I have also try with the "value" event but my "message.name" is empty.

How can I fix it?

like image 853
Max Avatar asked Jul 18 '14 12:07

Max


People also ask

How can I check if a value exists already in a Firebase data class Android?

child(busNum). exists() tests for the existence of a value at location BusNumber/<busNum> . It will not be true unless busNum is one of the keys created by push() .

How do you check if a user already exists in Firebase?

First, you should implement Firebase Authentication and then in order to check if a user exist in your database, you should use the following lines of code: String uid = FirebaseAuth. getInstance(). getCurrentUser().

What does getKey () do Firebase?

Calling the getKey() method on this reference will return the auto-generated key which may then be used to store a corresponding value. Using Firebase to generate unique keys in this way is also of particular use when an app has multiple users creating child nodes at the same path in the tree.


1 Answers

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');   } }); 
like image 168
Frank van Puffelen Avatar answered Sep 23 '22 15:09

Frank van Puffelen