Max Max - 2 years ago 117
Javascript Question

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('');
usersRef.on('child_added', function(snapshot) {
var message = snapshot.val();
if ( == 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 "" is empty.

How can I fix it?

Answer Source

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

usersRef.once('value', function(snapshot) {
  if (snapshot.hasChild(theDataToAdd)) {

Here's a quick jsfiddle showing how this works:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download