2013-02-16 93 views
0

我试图来检查用户名用作在火力地堡文档中给出的示例:查找数据火力地堡


function go() { 
    var userId = prompt('Username?', 'Guest'); 
    checkIfUserExists(userId); 
} 

var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users'; 

function userExistsCallback(userId, exists) { 
    if (exists) { 
    alert('user ' + userId + ' exists!'); 
    } else { 
    alert('user ' + userId + ' does not exist!'); 
    } 
} 

// Tests to see if /users/<userId> has any data. 
function checkIfUserExists(userId) { 
    var usersRef = new Firebase(USERS_LOCATION); 
    usersRef.child(userId).once('value', function(snapshot) { 
    var exists = (snapshot.val() !== null); 
    userExistsCallback(userId, exists); 
    }); 
} 

但我引用的数据是在

firebaseio.com/{userID}/primary/{username}

151(用户ID):即我有引用问题的数据的层|主页 |>用户名:用户名:

我想检查用户ID下的主树下的用户名字段...任何建议?

+0

嗨吉姆!我对你的结构有点困惑。如果我的用户ID是151,我的名字是“kato”,那么路径中的数据是'151/primary/kato/kato'?或者在你的例子中是{用户名}错误? – Kato 2013-02-16 15:26:34

回答

1

这是有点不清楚你的数据结构是什么;看到我上面的评论。使你的数据一对夫妇的假设,它看起来是这样的:

{151}/primary/username/{kato} 

凡在括号中的部分是可变位,剩下的就是一个固定键,那么你只需要如下更改路径:

// in checkIfUserExists 
usersRef.child(userId).child('primary/username').on('value', ...) 

如果没有用户ID,那么你可以遍历所有用户,并检查名称:

usersRef.once('value', function(ss) { 
    ss.forEach(function(childSnapshot) { 
     var userID = childSnapshot.name(); 
     childSnapshot.ref().child('primary/username').once('value', function(ss) { 
      var userName = ss.val(); 
      /* do something with name and ID here */ 
     }); 
    }); 
}); 

或者,如果你怀疑你的用户列表将是ludicro usly庞大(几千),您可能需要用户名指标到IDS在一个单独的路径,并避免任何重复:

userList/{username}/{userID} 

然后你可以使用方法如下:

userListRef.child(username).once('value', function(ss) { 
    var userID = ss.val(); 
    if(userID !== null) { 
     /* user exists and we have the name and id now */ 
    } 
}); 
+0

对不起 - 我的意思是{151}/primary/username/{kato} ...在你给出的解决方案中,因为我从来没有将用户名151命名为151并且从不提供用户ID,它将如何否循环遍历所有用户ID? 这是用户名,我试图比较不是userIDs? – 2013-02-16 22:17:49

+0

查看我的更新。我希望他们帮助:) – Kato 2013-02-16 22:34:48

+0

感谢它确实帮助 - 下面是尘埃落定时的外观:var userRef = new Firebase('https://j2000.firebaseio.com/users/'); var usernameRef = userRef.on ('child_added',function(userSnapshot){var userData = userSnapshot.val(); if(userData.primary.username === newusername){exists = newusername; userExistsCallback(exists);} else {exists = null; userExistsCallback (exists);} \t}); } – 2013-02-18 19:55:53