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?
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() .
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().
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.
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'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With