测试 Firebase 中是否存在数据 [英] Test if a data exist in Firebase

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

问题描述

在添加数据之前,我想测试 Firebase 中是否存在数据.但是我的方法有问题:我尝试使用此 Javascript 代码列出所有数据:

var theDataToAdd = userName;var usersRef = new Firebase('https://SampleChat.firebaseIO-demo.com/users/');usersRef.on('child_ added', 函数(快照){var message = snapshot.val();if (message.name == theDataToAdd)警报(存在");});

但是如果用户不存在,之前会添加,然后我的代码说他存在​​.你会说这是正常的,因为我的警报只有在child_ added"时才会被调用,但我不知道怎么做.

我也尝试过value"事件,但我的message.name"为空.

我该如何解决?

解决方案

您可以使用 DataSnapshot.hasChild 以确定某个孩子是否存在.

usersRef.once('value', function(snapshot) {如果(快照.hasChild(theDataToAdd)){警报('存在');}});

这是一个快速的 jsfiddle,展示了它是如何工作的:http://jsfiddle.net/PZ567/>

但是这会下载usersRef下的所有数据并在客户端执行检查.通过加载更有针对性的参考,仅下载您要检查的用户的数据会更有效率:

usersRef.child(theDataToAdd).once('value', function(snapshot) {如果(快照.存在()){警报('存在');}});

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/

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

这篇关于测试 Firebase 中是否存在数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆