测试Firebase中是否存在数据 [英] Test if a data exist in Firebase
问题描述
var theDataToAdd = userName;
var usersRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/');
usersRef.on('child_added',function(snapshot){
var message = snapshot.val(); $ b $ if(message.name == theDataToAdd)
alert(存在);
});
但是,如果用户不存在,它会被添加,然后我的代码说他存在。你会说这是正常的,因为我的警报只有在child_added时才被调用,但是我不知道怎么做。
我也试着用value事件,但我的message.name是空的。
我该如何解决它?
您可以使用 DataSnapshot.hasChild
来确定某个孩子是否存在。
usersRef.once ('value',function(snapshot){
if(snapshot.hasChild(theDataToAdd)){
alert('exists');
}
});
下面是一个快速的jsfiddle,它显示了这是如何工作的: http://jsfiddle.net/PZ567/
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?
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/
这篇关于测试Firebase中是否存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!