Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 67141  / 10 Years ago, fri, july 18, 2014, 12:00:00

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?


More From » firebase

 Answers
11

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

[#70158] Wednesday, July 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;