测试Firebase中是否存在数据

测试Firebase中是否存在数据

本文介绍了测试Firebase中是否存在数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试在Firebase中是否存在数据,然后添加它。但是我的方法有一个问题:我尝试使用这个Javascript代码列出所有数据:

  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是空的。



我该如何解决它?

解决方案

您可以使用来确定某个孩子是否存在。

  usersRef.once ('value',function(snapshot){
if(snapshot.hasChild(theDataToAdd)){
alert('exists');
}
});

下面是一个快速的jsfiddle,它显示了这是如何工作的:


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中是否存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:35